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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #use warnings; FIXME - Bug 2505
30 use C4
::Koha
; # XXX subfield_is_koha_internal_p
31 use C4
::Branch
; # XXX subfield_is_koha_internal_p
32 use C4
::BackgroundJob
;
37 use List
::MoreUtils qw
/uniq/;
40 my $dbh = C4
::Context
->dbh;
41 my $error = $input->param('error');
42 my @itemnumbers = $input->param('itemnumber');
43 my $biblionumber = $input->param('biblionumber');
44 my $op = $input->param('op');
45 my $del = $input->param('del');
46 my $del_records = $input->param('del_records');
47 my $completedJobID = $input->param('completedJobID');
48 my $runinbackground = $input->param('runinbackground');
49 my $src = $input->param('src');
50 my $use_default_values = $input->param('use_default_values');
55 $template_name = "tools/batchMod.tt";
56 $template_flag = { tools
=> '*' };
59 $template_name = ($del) ?
"tools/batchMod-del.tt" : "tools/batchMod-edit.tt";
60 $template_flag = ($del) ?
{ tools
=> 'items_batchdel' } : { tools
=> 'items_batchmod' };
64 my ($template, $loggedinuser, $cookie)
65 = get_template_and_user
({template_name
=> $template_name,
69 flagsrequired
=> $template_flag,
73 my $today_iso = C4
::Dates
->today('iso');
74 $template->param(today_iso
=> $today_iso);
75 $template->param(del
=> $del);
79 my @errors; # store errors found while checking data BEFORE saving item.
80 my $items_display_hashref;
81 my $tagslib = &GetMarcStructure
(1);
83 my $deleted_items = 0; # Number of deleted items
84 my $deleted_records = 0; # Number of deleted records ( with no items attached )
85 my $not_deleted_items = 0; # Number of items that could not be deleted
86 my @not_deleted; # List of the itemnumbers that could not be deleted
87 my $modified_items = 0; # Numbers of modified items
88 my $modified_fields = 0; # Numbers of modified fields
90 my %cookies = parse CGI
::Cookie
($cookie);
91 my $sessionID = $cookies{'CGISESSID'}->value;
94 #--- ----------------------------------------------------------------------------
95 if ($op eq "action") {
96 #-------------------------------------------------------------------------------
97 my @tags = $input->param('tag');
98 my @subfields = $input->param('subfield');
99 my @values = $input->param('field_value');
100 my @disabled = $input->param('disable_input');
101 # build indicator hash.
102 my @ind_tag = $input->param('ind_tag');
103 my @indicator = $input->param('indicator');
105 # Is there something to modify ?
106 # TODO : We shall use this var to warn the user in case no modification was done to the items
107 my $values_to_modify = scalar(grep {!/^$/} @values);
108 my $values_to_blank = scalar(@disabled);
111 # Once the job is done
112 if ($completedJobID) {
113 # If we have a reasonable amount of items, we display them
114 if (scalar(@itemnumbers) <= ( C4
::Context
->preference("MaxItemsForBatch") // 1000 ) ) {
115 $items_display_hashref=BuildItemsData
(@itemnumbers);
117 # Else, we only display the barcode
118 my @simple_items_display = map {{ itemnumber
=> $_, barcode
=> (GetBarcodeFromItemnumber
($_) or ""), biblionumber
=> (GetBiblionumberFromItemnumber
($_) or "") }} @itemnumbers;
119 $template->param("simple_items_display" => \
@simple_items_display);
122 # Setting the job as done
123 my $job = C4
::BackgroundJob
->fetch($sessionID, $completedJobID);
125 # Calling the template
126 add_saved_job_results_to_template
($template, $completedJobID);
129 # While the job is getting done
131 # Job size is the number of items we have to process
132 my $job_size = scalar(@itemnumbers);
135 # If we asked for background processing
136 if ($runinbackground) {
137 $job = put_in_background
($job_size);
140 #initializing values for updates
141 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField
("items.itemnumber", "");
142 if ($values_to_modify){
143 my $xml = TransformHtmlToXml
(\
@tags,\
@subfields,\
@values,\
@indicator,\
@ind_tag, 'ITEM');
144 $marcitem = MARC
::Record
::new_from_xml
($xml, 'UTF-8');
146 if ($values_to_blank){
147 foreach my $disabledsubf (@disabled){
148 if ($marcitem && $marcitem->field($itemtagfield)){
149 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
152 $marcitem = MARC
::Record
->new();
153 $marcitem->append_fields( MARC
::Field
->new( $itemtagfield, '', '', $disabledsubf => "" ) );
160 foreach my $itemnumber(@itemnumbers){
162 $job->progress($i) if $runinbackground;
163 my $itemdata = GetItem
($itemnumber);
165 my $return = DelItemCheck
(C4
::Context
->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
169 $not_deleted_items++;
171 { biblionumber
=> $itemdata->{'biblionumber'},
172 itemnumber
=> $itemdata->{'itemnumber'},
173 barcode
=> $itemdata->{'barcode'},
174 title
=> $itemdata->{'title'},
179 # If there are no items left, delete the biblio
180 if ( $del_records ) {
181 my $itemscount = GetItemsCount
($itemdata->{'biblionumber'});
182 if ( $itemscount == 0 ) {
183 my $error = DelBiblio
($itemdata->{'biblionumber'});
184 $deleted_records++ unless ( $error );
188 if ($values_to_modify || $values_to_blank) {
189 my $localmarcitem = Item2Marc
($itemdata);
191 my $modified = UpdateMarcWith
( $marcitem, $localmarcitem );
194 if ( my $item = ModItemFromMarc
( $localmarcitem, $itemdata->{biblionumber
}, $itemnumber ) ) {
195 LostItem
($itemnumber, 'MARK RETURNED') if $item->{itemlost
};
199 if ( $runinbackground ) {
200 $modified_items++ if $modified;
201 $modified_fields += $modified;
203 modified_items
=> $modified_items,
204 modified_fields
=> $modified_fields,
214 #-------------------------------------------------------------------------------
215 # build screen with existing items. and "new" one
216 #-------------------------------------------------------------------------------
219 my $filefh = $input->upload('uploadfile');
220 my $filecontent = $input->param('filecontent');
221 my @notfoundbarcodes;
225 while (my $content=<$filefh>){
226 $content =~ s/[\r\n]*$//;
227 push @contentlist, $content if $content;
230 if ($filecontent eq 'barcode_file') {
231 foreach my $barcode (@contentlist) {
233 my $itemnumber = GetItemnumberFromBarcode
($barcode);
235 push @itemnumbers,$itemnumber;
237 push @notfoundbarcodes, $barcode;
241 elsif ( $filecontent eq 'itemid_file') {
242 @itemnumbers = @contentlist;
245 if (defined $biblionumber){
246 my @all_items = GetItemsInfo
( $biblionumber );
247 foreach my $itm (@all_items) {
248 push @itemnumbers, $itm->{itemnumber
};
251 if ( my $list=$input->param('barcodelist')){
252 push my @barcodelist, uniq
( split(/\s\n/, $list) );
254 foreach my $barcode (@barcodelist) {
256 my $itemnumber = GetItemnumberFromBarcode
($barcode);
258 push @itemnumbers,$itemnumber;
260 push @notfoundbarcodes, $barcode;
267 # Flag to tell the template there are valid results, hidden or not
268 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
269 # Only display the items if there are no more than pref MaxItemsForBatch
270 if (scalar(@itemnumbers) <= ( C4
::Context
->preference("MaxItemsForBatch") // 1000 ) ) {
271 $items_display_hashref=BuildItemsData
(@itemnumbers);
273 $template->param("too_many_items" => scalar(@itemnumbers));
274 # Even if we do not display the items, we need the itemnumbers
275 $template->param(itemnumbers_array
=> \
@itemnumbers);
277 # now, build the item form for entering a new item
280 my $branch_limit = C4
::Context
->userenv ? C4
::Context
->userenv->{"branch"} : "";
281 my $query = qq{SELECT authorised_value
, lib FROM authorised_values
};
282 $query .= qq{ LEFT JOIN authorised_values_branches ON
( id
= av_id
) } if $branch_limit;
283 $query .= qq{ WHERE category
= ?
};
284 $query .= qq{ AND
( branchcode
= ? OR branchcode IS NULL
) } if $branch_limit;
285 $query .= qq{ GROUP BY lib ORDER BY lib
, lib_opac
};
286 my $authorised_values_sth = $dbh->prepare( $query );
288 my $branches = GetBranchesLoop
(); # build once ahead of time, instead of multiple times later.
290 # Adding a default choice, in case the user does not want to modify the branch
291 my $nochange_branch = { branchname
=> '', value
=> '', selected
=> 1 };
292 unshift (@
$branches, $nochange_branch);
294 my $pref_itemcallnumber = C4
::Context
->preference('itemcallnumber');
297 foreach my $tag (sort keys %{$tagslib}) {
298 # loop through each subfield
299 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
300 next if subfield_is_koha_internal_p
($subfield);
301 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
302 # barcode and stocknumber are not meant to be batch-modified
303 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
304 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
307 my $index_subfield = int(rand(1000000));
308 if ($subfield eq '@'){
309 $subfield_data{id
} = "tag_".$tag."_subfield_00_".$index_subfield;
311 $subfield_data{id
} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
313 $subfield_data{tag
} = $tag;
314 $subfield_data{subfield
} = $subfield;
315 $subfield_data{random
} = int(rand(1000000)); # why do we need 2 different randoms?
316 # $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
317 $subfield_data{marc_lib
} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib
}."\">".$tagslib->{$tag}->{$subfield}->{lib
}."</span>";
318 $subfield_data{mandatory
} = $tagslib->{$tag}->{$subfield}->{mandatory
};
319 $subfield_data{repeatable
} = $tagslib->{$tag}->{$subfield}->{repeatable
};
321 $value =~ s/"/"/g;
322 if ( !$value && $use_default_values) {
323 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue
};
324 # get today date & replace YYYY, MM, DD if provided in the default value
325 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
326 $value =~ s/YYYY/$year/g;
327 $value =~ s/MM/$month/g;
328 $value =~ s/DD/$day/g;
330 $subfield_data{visibility
} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden
} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden
} < -4));
331 # testing branch value if IndependentBranches.
333 if ( $tagslib->{$tag}->{$subfield}->{authorised_value
} ) {
334 my @authorised_values;
336 # builds list, depending on authorised value...
338 if ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "branches" ) {
339 foreach my $thisbranch (@
$branches) {
340 push @authorised_values, $thisbranch->{value
};
341 $authorised_lib{$thisbranch->{value
}} = $thisbranch->{branchname
};
345 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "itemtypes" ) {
346 push @authorised_values, "";
347 my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
349 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
350 push @authorised_values, $itemtype;
351 $authorised_lib{$itemtype} = $description;
357 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "cn_source" ) {
358 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
360 my $class_sources = GetClassSources
();
361 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
363 foreach my $class_source (sort keys %$class_sources) {
364 next unless $class_sources->{$class_source}->{'used'} or
365 ($value and $class_source eq $value) or
366 ($class_source eq $default_source);
367 push @authorised_values, $class_source;
368 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
372 #---- "true" authorised value
375 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
376 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value
}, $branch_limit ?
$branch_limit : () );
377 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
378 push @authorised_values, $value;
379 $authorised_lib{$value} = $lib;
383 $subfield_data{marc_value
} = {
385 id
=> "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
386 name
=> "field_value",
387 values => \
@authorised_values,
388 labels
=> \
%authorised_lib,
391 # it's a thesaurus / authority field
393 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode
} ) {
394 $subfield_data{marc_value
} = {
396 id
=> $subfield_data{id
},
398 authtypecode
=> $tagslib->{$tag}->{$subfield}->{authtypecode
},
400 # it's a plugin field
402 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder
} ) {
404 my $plugin = C4
::Context
->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
407 my $extended_param = plugin_parameters
( $dbh, $temp, $tagslib, $subfield_data{id
}, \
@loop_data );
408 my ( $function_name, $javascript ) = plugin_javascript
( $dbh, $temp, $tagslib, $subfield_data{id
}, \
@loop_data );
409 $subfield_data{marc_value
} = {
411 id
=> $subfield_data{id
},
413 function
=> $function_name,
414 random
=> $subfield_data{random
},
415 javascript
=> $javascript,
418 warn "Plugin Failed: $plugin";
419 $subfield_data{marc_value
} = { # supply default input form
421 id
=> $subfield_data{id
},
426 elsif ( $tag eq '' ) { # it's an hidden field
427 $subfield_data{marc_value
} = {
429 id
=> $subfield_data{id
},
433 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
434 $subfield_data{marc_value
} = {
436 id
=> $subfield_data{id
},
440 elsif ( length($value) > 100
441 or (C4
::Context
->preference("marcflavour") eq "UNIMARC" and
442 300 <= $tag && $tag < 400 && $subfield eq 'a' )
443 or (C4
::Context
->preference("marcflavour") eq "MARC21" and
444 500 <= $tag && $tag < 600 )
446 # oversize field (textarea)
447 $subfield_data{marc_value
} = {
449 id
=> $subfield_data{id
},
453 # it's a standard field
454 $subfield_data{marc_value
} = {
456 id
=> $subfield_data{id
},
460 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
461 push (@loop_data, \
%subfield_data);
464 } # -- End foreach tag
465 $authorised_values_sth->finish;
469 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
470 $template->param(item
=> \
@loop_data);
471 if (@notfoundbarcodes) {
472 my @notfoundbarcodesloop = map{{barcode
=>$_}}@notfoundbarcodes;
473 $template->param(notfoundbarcodes
=> \
@notfoundbarcodesloop);
476 } # -- End action="show"
478 $template->param(%$items_display_hashref) if $items_display_hashref;
482 $template->param( $op => 1 ) if $op;
484 if ($op eq "action") {
486 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
489 not_deleted_items
=> $not_deleted_items,
490 deleted_items
=> $deleted_items,
491 delete_records
=> $del_records,
492 deleted_records
=> $deleted_records,
493 not_deleted_loop
=> \
@not_deleted
497 foreach my $error (@errors) {
498 $template->param($error => 1) if $error;
500 $template->param(src
=> $src);
501 $template->param(biblionumber
=> $biblionumber);
502 output_html_with_http_headers
$input, $cookie, $template->output;
506 # ---------------- Functions
510 # now, build existiing item list
511 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
513 #---- finds where items.itemnumber is stored
514 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField
("items.itemnumber", "");
515 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField
("items.homebranch", "");
516 foreach my $itemnumber (@itemnumbers){
517 my $itemdata=GetItem
($itemnumber);
518 my $itemmarc=Item2Marc
($itemdata);
520 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
521 # loop through each subfield
522 my $itembranchcode=$field->subfield($branchtagsubfield);
523 if ($itembranchcode && C4
::Context
->preference("IndependentBranches")) {
525 my $userenv = C4
::Context
->userenv();
526 unless (C4
::Context
->IsSuperLibrarian() or (($userenv->{'branch'} eq $itembranchcode))){
527 $this_row{'nomod'}=1;
530 my $tag=$field->tag();
531 foreach my $subfield ($field->subfields) {
532 my ($subfcode,$subfvalue)=@
$subfield;
533 next if ($tagslib->{$tag}->{$subfcode}->{tab
} ne 10
534 && $tag ne $itemtagfield
535 && $subfcode ne $itemtagsubfield);
537 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib
} if ($tagslib->{$tag}->{$subfcode}->{tab
} eq 10);
538 if ($tagslib->{$tag}->{$subfcode}->{tab
} eq 10) {
539 $this_row{$subfcode}=GetAuthorisedValueDesc
( $tag,
540 $subfcode, $subfvalue, '', $tagslib)
544 $this_row{itemnumber
} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
548 # grab title, author, and ISBN to identify bib that the item
549 # belongs to in the display
550 my $biblio=GetBiblioData
($$itemdata{biblionumber
});
551 $this_row{title
} = $biblio->{title
};
552 $this_row{author
} = $biblio->{author
};
553 $this_row{isbn
} = $biblio->{isbn
};
554 $this_row{biblionumber
} = $biblio->{biblionumber
};
557 push(@big_array, \
%this_row);
560 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
562 # now, construct template !
563 # First, the existing items for display
565 my @witnesscodessorted=sort keys %witness;
566 for my $row ( @big_array ) {
568 my @item_fields = map +{ field
=> $_ || '' }, @
$row{ @witnesscodessorted };
569 $row_data{item_value
} = [ @item_fields ];
570 $row_data{itemnumber
} = $row->{itemnumber
};
571 #reporting this_row values
572 $row_data{'nomod'} = $row->{'nomod'};
573 $row_data{bibinfo
} = $row->{bibinfo
};
574 $row_data{author
} = $row->{author
};
575 $row_data{title
} = $row->{title
};
576 $row_data{isbn
} = $row->{isbn
};
577 $row_data{biblionumber
} = $row->{biblionumber
};
578 my $is_on_loan = C4
::Circulation
::IsItemIssued
( $row->{itemnumber
} );
579 $row_data{onloan
} = $is_on_loan ?
1 : 0;
580 push(@item_value_loop,\
%row_data);
582 my @header_loop=map { { header_value
=> $witness{$_}} } @witnesscodessorted;
584 return { item_loop
=> \
@item_value_loop, item_header_loop
=> \
@header_loop };
587 #BE WARN : it is not the general case
588 # This function can be OK in the item marc record special case
589 # Where subfield is not repeated
590 # And where we are sure that field should correspond
593 my ($marcfrom,$marcto)=@_;
594 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField
("items.itemnumber", "");
595 my $fieldfrom=$marcfrom->field($itemtag);
596 my @fields_to=$marcto->field($itemtag);
598 foreach my $subfield ( $fieldfrom->subfields() ) {
599 foreach my $field_to_update ( @fields_to ) {
600 if ( $subfield->[1] ) {
601 unless ( $field_to_update->subfield($subfield->[0]) eq $subfield->[1] ) {
603 $field_to_update->update( $subfield->[0] => $subfield->[1] );
608 $field_to_update->delete_subfield( code
=> $subfield->[0] );
616 my ($tagfield,$insubfield,$record) = @_;
619 foreach my $field ($record->field($tagfield)) {
620 my @subfields = $field->subfields();
621 foreach my $subfield (@subfields) {
622 if (@
$subfield[0] eq $insubfield) {
623 $result .= @
$subfield[1];
624 $indicator = $field->indicator(1).$field->indicator(2);
628 return($indicator,$result);
631 # ----------------------------
632 # Background functions
635 sub add_results_to_template
{
636 my $template = shift;
638 $template->param(map { $_ => $results->{$_} } keys %{ $results });
641 sub add_saved_job_results_to_template
{
642 my $template = shift;
643 my $completedJobID = shift;
644 my $job = C4
::BackgroundJob
->fetch($sessionID, $completedJobID);
645 my $results = $job->results();
646 add_results_to_template
($template, $results);
648 my $fields = $job->get("modified_fields");
649 my $items = $job->get("modified_items");
651 modified_items
=> $items,
652 modified_fields
=> $fields,
656 sub put_in_background
{
657 my $job_size = shift;
659 my $job = C4
::BackgroundJob
->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
660 my $jobID = $job->id();
663 if (my $pid = fork) {
665 # return job ID as JSON
667 # prevent parent exiting from
668 # destroying the kid's database handle
669 # FIXME: according to DBI doc, this may not work for Oracle
670 $dbh->{InactiveDestroy
} = 1;
672 my $reply = CGI
->new("");
673 print $reply->header(-type
=> 'text/html');
674 print '{"jobID":"' . $jobID . '"}';
676 } elsif (defined $pid) {
678 # close STDOUT to signal to Apache that
679 # we're now running in the background
683 # fork failed, so exit immediately
684 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";