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/;
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 ? GetMember( borrowernumber => $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);
128 { itemnumber => $itemnumber, barcode => ($item->barcode || q||), biblionumber => $item->biblio->biblionumber }} @itemnumbers;
129 $template->param("simple_items_display" => \@simple_items_display);
132 # Setting the job as done
133 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
135 # Calling the template
136 add_saved_job_results_to_template($template, $completedJobID);
139 # While the job is getting done
141 # Job size is the number of items we have to process
142 my $job_size = scalar(@itemnumbers);
145 # If we asked for background processing
146 if ($runinbackground) {
147 $job = put_in_background($job_size);
150 #initializing values for updates
151 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
152 if ($values_to_modify){
153 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
154 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
156 if ($values_to_blank){
157 foreach my $disabledsubf (@disabled){
158 if ($marcitem && $marcitem->field($itemtagfield)){
159 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
162 $marcitem = MARC::Record->new();
163 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
170 foreach my $itemnumber(@itemnumbers){
172 $job->progress($i) if $runinbackground;
173 my $itemdata = GetItem($itemnumber);
175 my $return = DelItemCheck( $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
179 $not_deleted_items++;
181 { biblionumber => $itemdata->{'biblionumber'},
182 itemnumber => $itemdata->{'itemnumber'},
183 barcode => $itemdata->{'barcode'},
184 title => $itemdata->{'title'},
189 # If there are no items left, delete the biblio
190 if ( $del_records ) {
191 my $itemscount = Koha::Biblios->find( $itemdata->{'biblionumber'} )->items->count;
192 if ( $itemscount == 0 ) {
193 my $error = DelBiblio($itemdata->{'biblionumber'});
194 $deleted_records++ unless ( $error );
198 if ($values_to_modify || $values_to_blank) {
199 my $localmarcitem = Item2Marc($itemdata);
201 my $modified = UpdateMarcWith( $marcitem, $localmarcitem );
204 if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
205 LostItem($itemnumber, 'MARK RETURNED') if $item->{itemlost} and not $itemdata->{itemlost};
209 if ( $runinbackground ) {
210 $modified_items++ if $modified;
211 $modified_fields += $modified;
213 modified_items => $modified_items,
214 modified_fields => $modified_fields,
224 #-------------------------------------------------------------------------------
225 # build screen with existing items. and "new" one
226 #-------------------------------------------------------------------------------
229 my $filefh = $input->upload('uploadfile');
230 my $filecontent = $input->param('filecontent');
231 my @notfoundbarcodes;
235 while (my $content=<$filefh>){
236 $content =~ s/[\r\n]*$//;
237 push @contentlist, $content if $content;
240 if ($filecontent eq 'barcode_file') {
241 foreach my $barcode (@contentlist) {
243 my $itemnumber = GetItemnumberFromBarcode($barcode);
245 push @itemnumbers,$itemnumber;
247 push @notfoundbarcodes, $barcode;
251 elsif ( $filecontent eq 'itemid_file') {
252 @itemnumbers = @contentlist;
255 if (defined $biblionumber){
256 my @all_items = GetItemsInfo( $biblionumber );
257 foreach my $itm (@all_items) {
258 push @itemnumbers, $itm->{itemnumber};
261 if ( my $list=$input->param('barcodelist')){
262 push my @barcodelist, uniq( split(/\s\n/, $list) );
264 foreach my $barcode (@barcodelist) {
266 my $itemnumber = GetItemnumberFromBarcode($barcode);
268 push @itemnumbers,$itemnumber;
270 push @notfoundbarcodes, $barcode;
277 # Flag to tell the template there are valid results, hidden or not
278 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
279 # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel
281 ? C4::Context->preference("MaxItemsToDisplayForBatchDel")
282 : C4::Context->preference("MaxItemsToProcessForBatchMod");
283 if (scalar(@itemnumbers) <= ( $max_items // 1000 ) ) {
284 $items_display_hashref=BuildItemsData(@itemnumbers);
286 $template->param("too_many_items" => scalar(@itemnumbers));
287 # Even if we do not display the items, we need the itemnumbers
288 $template->param(itemnumbers_array => \@itemnumbers);
290 # now, build the item form for entering a new item
293 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
294 my $query = qq{SELECT authorised_value, lib FROM authorised_values};
295 $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id ) } if $branch_limit;
296 $query .= qq{ WHERE category = ?};
297 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL ) } if $branch_limit;
298 $query .= qq{ GROUP BY lib ORDER BY lib, lib_opac};
299 my $authorised_values_sth = $dbh->prepare( $query );
301 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
303 # Adding a default choice, in case the user does not want to modify the branch
304 my $nochange_branch = { branchname => '', value => '', selected => 1 };
305 unshift (@$libraries, $nochange_branch);
307 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
309 # Getting list of subfields to keep when restricted batchmod edit is enabled
310 my $subfieldsToAllowForBatchmod = C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod');
311 my $allowAllSubfields = (
312 not defined $subfieldsToAllowForBatchmod
313 or $subfieldsToAllowForBatchmod == q||
315 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForBatchmod);
317 foreach my $tag (sort keys %{$tagslib}) {
318 # loop through each subfield
319 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
320 next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} );
321 next if (not $allowAllSubfields and $restrictededition && !grep { $tag . '$' . $subfield eq $_ } @subfieldsToAllow );
322 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
323 # barcode and stocknumber are not meant to be batch-modified
324 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
325 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
328 my $index_subfield = int(rand(1000000));
329 if ($subfield eq '@'){
330 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
332 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
334 $subfield_data{tag} = $tag;
335 $subfield_data{subfield} = $subfield;
336 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
337 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
338 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
340 $value =~ s/"/"/g;
341 if ( !$value && $use_default_values) {
342 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
343 # get today date & replace YYYY, MM, DD if provided in the default value
344 my $today = dt_from_string;
345 my $year = $today->year;
346 my $month = $today->month;
347 my $day = $today->day;
348 $value =~ s/YYYY/$year/g;
349 $value =~ s/MM/$month/g;
350 $value =~ s/DD/$day/g;
352 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
353 # testing branch value if IndependentBranches.
355 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
356 my @authorised_values;
358 # builds list, depending on authorised value...
360 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
361 foreach my $library (@$libraries) {
362 push @authorised_values, $library->{branchcode};
363 $authorised_lib{$library->{branchcode}} = $library->{branchname};
367 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
368 push @authorised_values, "";
369 my $itemtypes = Koha::ItemTypes->search_with_localization;
370 while ( my $itemtype = $itemtypes->next ) {
371 push @authorised_values, $itemtype->itemtype;
372 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
378 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
379 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
381 my $class_sources = GetClassSources();
382 my $default_source = C4::Context->preference("DefaultClassificationSource");
384 foreach my $class_source (sort keys %$class_sources) {
385 next unless $class_sources->{$class_source}->{'used'} or
386 ($value and $class_source eq $value) or
387 ($class_source eq $default_source);
388 push @authorised_values, $class_source;
389 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
393 #---- "true" authorised value
396 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
397 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value}, $branch_limit ? $branch_limit : () );
398 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
399 push @authorised_values, $value;
400 $authorised_lib{$value} = $lib;
404 $subfield_data{marc_value} = {
406 id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
407 name => "field_value",
408 values => \@authorised_values,
409 labels => \%authorised_lib,
412 # it's a thesaurus / authority field
414 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
415 $subfield_data{marc_value} = {
417 id => $subfield_data{id},
419 authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode},
422 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) { # plugin
423 require Koha::FrameworkPlugin;
424 my $plugin = Koha::FrameworkPlugin->new( {
425 name => $tagslib->{$tag}->{$subfield}->{'value_builder'},
429 my $pars= { dbh => $dbh, record => $temp, tagslib => $tagslib,
430 id => $subfield_data{id}, tabloop => \@loop_data };
431 $plugin->build( $pars );
432 if( !$plugin->errstr ) {
433 $subfield_data{marc_value} = {
435 id => $subfield_data{id},
437 javascript => $plugin->javascript,
438 noclick => $plugin->noclick,
441 warn $plugin->errstr;
442 $subfield_data{marc_value} = { # supply default input form
444 id => $subfield_data{id},
449 elsif ( $tag eq '' ) { # it's an hidden field
450 $subfield_data{marc_value} = {
452 id => $subfield_data{id},
456 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
457 $subfield_data{marc_value} = {
459 id => $subfield_data{id},
463 elsif ( length($value) > 100
464 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
465 300 <= $tag && $tag < 400 && $subfield eq 'a' )
466 or (C4::Context->preference("marcflavour") eq "MARC21" and
467 500 <= $tag && $tag < 600 )
469 # oversize field (textarea)
470 $subfield_data{marc_value} = {
472 id => $subfield_data{id},
476 # it's a standard field
477 $subfield_data{marc_value} = {
479 id => $subfield_data{id},
483 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
484 push (@loop_data, \%subfield_data);
487 } # -- End foreach tag
488 $authorised_values_sth->finish;
492 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
493 $template->param(item => \@loop_data);
494 if (@notfoundbarcodes) {
495 my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
496 $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
499 } # -- End action="show"
501 $template->param(%$items_display_hashref) if $items_display_hashref;
505 $template->param( $op => 1 ) if $op;
507 if ($op eq "action") {
509 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
512 not_deleted_items => $not_deleted_items,
513 deleted_items => $deleted_items,
514 delete_records => $del_records,
515 deleted_records => $deleted_records,
516 not_deleted_loop => \@not_deleted
520 foreach my $error (@errors) {
521 $template->param($error => 1) if $error;
523 $template->param(src => $src);
524 $template->param(biblionumber => $biblionumber);
525 output_html_with_http_headers $input, $cookie, $template->output;
529 # ---------------- Functions
533 # now, build existiing item list
534 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
536 #---- finds where items.itemnumber is stored
537 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
538 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
539 foreach my $itemnumber (@itemnumbers){
540 my $itemdata=GetItem($itemnumber);
541 my $itemmarc=Item2Marc($itemdata);
543 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
544 # loop through each subfield
545 my $itembranchcode=$field->subfield($branchtagsubfield);
546 if ($itembranchcode && C4::Context->preference("IndependentBranches")) {
548 my $userenv = C4::Context->userenv();
549 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
550 $this_row{'nomod'}=1;
553 my $tag=$field->tag();
554 foreach my $subfield ($field->subfields) {
555 my ($subfcode,$subfvalue)=@$subfield;
556 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
557 && $tag ne $itemtagfield
558 && $subfcode ne $itemtagsubfield);
560 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
561 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
562 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
563 $subfcode, $subfvalue, '', $tagslib)
567 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
571 # grab title, author, and ISBN to identify bib that the item
572 # belongs to in the display
573 my $biblio=GetBiblioData($$itemdata{biblionumber});
574 $this_row{title} = $biblio->{title};
575 $this_row{author} = $biblio->{author};
576 $this_row{isbn} = $biblio->{isbn};
577 $this_row{biblionumber} = $biblio->{biblionumber};
580 push(@big_array, \%this_row);
583 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
585 # now, construct template !
586 # First, the existing items for display
588 my @witnesscodessorted=sort keys %witness;
589 for my $row ( @big_array ) {
591 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
592 $row_data{item_value} = [ @item_fields ];
593 $row_data{itemnumber} = $row->{itemnumber};
594 #reporting this_row values
595 $row_data{'nomod'} = $row->{'nomod'};
596 $row_data{bibinfo} = $row->{bibinfo};
597 $row_data{author} = $row->{author};
598 $row_data{title} = $row->{title};
599 $row_data{isbn} = $row->{isbn};
600 $row_data{biblionumber} = $row->{biblionumber};
601 my $is_on_loan = C4::Circulation::IsItemIssued( $row->{itemnumber} );
602 $row_data{onloan} = $is_on_loan ? 1 : 0;
603 push(@item_value_loop,\%row_data);
605 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
607 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
610 #BE WARN : it is not the general case
611 # This function can be OK in the item marc record special case
612 # Where subfield is not repeated
613 # And where we are sure that field should correspond
616 my ($marcfrom,$marcto)=@_;
617 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
618 my $fieldfrom=$marcfrom->field($itemtag);
619 my @fields_to=$marcto->field($itemtag);
621 foreach my $subfield ( $fieldfrom->subfields() ) {
622 foreach my $field_to_update ( @fields_to ) {
623 if ( $subfield->[1] ) {
624 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
626 $field_to_update->update( $subfield->[0] => $subfield->[1] );
631 $field_to_update->delete_subfield( code => $subfield->[0] );
639 my ($tagfield,$insubfield,$record) = @_;
642 foreach my $field ($record->field($tagfield)) {
643 my @subfields = $field->subfields();
644 foreach my $subfield (@subfields) {
645 if (@$subfield[0] eq $insubfield) {
646 $result .= @$subfield[1];
647 $indicator = $field->indicator(1).$field->indicator(2);
651 return($indicator,$result);
654 # ----------------------------
655 # Background functions
658 sub add_results_to_template {
659 my $template = shift;
661 $template->param(map { $_ => $results->{$_} } keys %{ $results });
664 sub add_saved_job_results_to_template {
665 my $template = shift;
666 my $completedJobID = shift;
667 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
668 my $results = $job->results();
669 add_results_to_template($template, $results);
671 my $fields = $job->get("modified_fields");
672 my $items = $job->get("modified_items");
674 modified_items => $items,
675 modified_fields => $fields,
679 sub put_in_background {
680 my $job_size = shift;
682 my $job = C4::BackgroundJob->new($sessionID, "test", '/cgi-bin/koha/tools/batchMod.pl', $job_size);
683 my $jobID = $job->id();
686 if (my $pid = fork) {
688 # return job ID as JSON
690 # prevent parent exiting from
691 # destroying the kid's database handle
692 # FIXME: according to DBI doc, this may not work for Oracle
693 $dbh->{InactiveDestroy} = 1;
695 my $reply = CGI->new("");
696 print $reply->header(-type => 'text/html');
697 print '{"jobID":"' . $jobID . '"}';
699 } elsif (defined $pid) {
701 # close STDOUT to signal to Apache that
702 # we're now running in the background
706 # fork failed, so exit immediately
707 warn "fork failed while attempting to run tools/batchMod.pl as a background job";