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.tmpl";
56 $template_flag = { tools
=> '*' };
59 $template_name = ($del) ?
"tools/batchMod-del.tmpl" : "tools/batchMod-edit.tmpl";
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) <= 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');
145 $marcitem = MARC
::Record
::new_from_xml
($xml, 'UTF-8');
147 if ($values_to_blank){
148 foreach my $disabledsubf (@disabled){
149 if ($marcitem && $marcitem->field($itemtagfield)){
150 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
153 $marcitem = MARC
::Record
->new();
154 $marcitem->append_fields( MARC
::Field
->new( $itemtagfield, '', '', $disabledsubf => "" ) );
161 foreach my $itemnumber(@itemnumbers){
163 $job->progress($i) if $runinbackground;
164 my $itemdata = GetItem
($itemnumber);
166 my $return = DelItemCheck
(C4
::Context
->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
170 $not_deleted_items++;
172 { biblionumber
=> $itemdata->{'biblionumber'},
173 itemnumber
=> $itemdata->{'itemnumber'},
174 barcode
=> $itemdata->{'barcode'},
175 title
=> $itemdata->{'title'},
180 # If there are no items left, delete the biblio
181 if ( $del_records ) {
182 my $itemscount = GetItemsCount
($itemdata->{'biblionumber'});
183 if ( $itemscount == 0 ) {
184 my $error = DelBiblio
($itemdata->{'biblionumber'});
185 $deleted_records++ unless ( $error );
189 if ($values_to_modify || $values_to_blank) {
190 my $localmarcitem = Item2Marc
($itemdata);
192 my $modified = UpdateMarcWith
( $marcitem, $localmarcitem );
195 if ( my $item = ModItemFromMarc
( $localmarcitem, $itemdata->{biblionumber
}, $itemnumber ) ) {
196 LostItem
($itemnumber, 'MARK RETURNED') if $item->{itemlost
};
200 if ( $runinbackground ) {
201 $modified_items++ if $modified;
202 $modified_fields += $modified;
204 modified_items
=> $modified_items,
205 modified_fields
=> $modified_fields,
215 #-------------------------------------------------------------------------------
216 # build screen with existing items. and "new" one
217 #-------------------------------------------------------------------------------
220 my $filefh = $input->upload('uploadfile');
221 my $filecontent = $input->param('filecontent');
222 my @notfoundbarcodes;
226 while (my $content=<$filefh>){
227 $content =~ s/[\r\n]*$//;
228 push @contentlist, $content if $content;
231 if ($filecontent eq 'barcode_file') {
232 foreach my $barcode (@contentlist) {
234 my $itemnumber = GetItemnumberFromBarcode
($barcode);
236 push @itemnumbers,$itemnumber;
238 push @notfoundbarcodes, $barcode;
242 elsif ( $filecontent eq 'itemid_file') {
243 @itemnumbers = @contentlist;
246 if (defined $biblionumber){
247 my @all_items = GetItemsInfo
( $biblionumber );
248 foreach my $itm (@all_items) {
249 push @itemnumbers, $itm->{itemnumber
};
252 if ( my $list=$input->param('barcodelist')){
253 push my @barcodelist, uniq
( split(/\s\n/, $list) );
255 foreach my $barcode (@barcodelist) {
257 my $itemnumber = GetItemnumberFromBarcode
($barcode);
259 push @itemnumbers,$itemnumber;
261 push @notfoundbarcodes, $barcode;
268 # Flag to tell the template there are valid results, hidden or not
269 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
270 # Only display the items if there are no more than 1000
271 if (scalar(@itemnumbers) <= 1000) {
272 $items_display_hashref=BuildItemsData
(@itemnumbers);
274 $template->param("too_many_items" => scalar(@itemnumbers));
275 # Even if we do not display the items, we need the itemnumbers
276 $template->param(itemnumbers_array
=> \
@itemnumbers);
278 # now, build the item form for entering a new item
281 my $branch_limit = C4
::Context
->userenv ? C4
::Context
->userenv->{"branch"} : "";
282 my $query = qq{SELECT authorised_value
, lib FROM authorised_values
};
283 $query .= qq{ LEFT JOIN authorised_values_branches ON
( id
= av_id
) } if $branch_limit;
284 $query .= qq{ WHERE category
= ?
};
285 $query .= qq{ AND
( branchcode
= ? OR branchcode IS NULL
) } if $branch_limit;
286 $query .= qq{ GROUP BY lib ORDER BY lib
, lib_opac
};
287 my $authorised_values_sth = $dbh->prepare( $query );
289 my $branches = GetBranchesLoop
(); # build once ahead of time, instead of multiple times later.
291 # Adding a default choice, in case the user does not want to modify the branch
292 my $nochange_branch = { branchname
=> '', value
=> '', selected
=> 1 };
293 unshift (@
$branches, $nochange_branch);
295 my $pref_itemcallnumber = C4
::Context
->preference('itemcallnumber');
298 foreach my $tag (sort keys %{$tagslib}) {
299 # loop through each subfield
300 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
301 next if subfield_is_koha_internal_p
($subfield);
302 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
303 # barcode and stocknumber are not meant to be batch-modified
304 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
305 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
308 my $index_subfield = int(rand(1000000));
309 if ($subfield eq '@'){
310 $subfield_data{id
} = "tag_".$tag."_subfield_00_".$index_subfield;
312 $subfield_data{id
} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
314 $subfield_data{tag
} = $tag;
315 $subfield_data{subfield
} = $subfield;
316 $subfield_data{random
} = int(rand(1000000)); # why do we need 2 different randoms?
317 # $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
318 $subfield_data{marc_lib
} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib
}."\">".$tagslib->{$tag}->{$subfield}->{lib
}."</span>";
319 $subfield_data{mandatory
} = $tagslib->{$tag}->{$subfield}->{mandatory
};
320 $subfield_data{repeatable
} = $tagslib->{$tag}->{$subfield}->{repeatable
};
322 $value =~ s/"/"/g;
323 if ( !$value && $use_default_values) {
324 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue
};
325 # get today date & replace YYYY, MM, DD if provided in the default value
326 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
327 $value =~ s/YYYY/$year/g;
328 $value =~ s/MM/$month/g;
329 $value =~ s/DD/$day/g;
331 $subfield_data{visibility
} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden
} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden
} < -4));
332 # testing branch value if IndependentBranches.
334 my $attributes_no_value = qq(tabindex
="1" id
="$subfield_data{id}" name
="field_value" class="input_marceditor" size
="50" maxlength
="255" );
335 my $attributes = qq($attributes_no_value value
="$value" );
337 if ( $tagslib->{$tag}->{$subfield}->{authorised_value
} ) {
338 my @authorised_values;
340 # builds list, depending on authorised value...
342 if ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "branches" ) {
343 foreach my $thisbranch (@
$branches) {
344 push @authorised_values, $thisbranch->{value
};
345 $authorised_lib{$thisbranch->{value
}} = $thisbranch->{branchname
};
349 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "itemtypes" ) {
350 push @authorised_values, "";
351 my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
353 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
354 push @authorised_values, $itemtype;
355 $authorised_lib{$itemtype} = $description;
361 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "cn_source" ) {
362 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
364 my $class_sources = GetClassSources
();
365 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
367 foreach my $class_source (sort keys %$class_sources) {
368 next unless $class_sources->{$class_source}->{'used'} or
369 ($value and $class_source eq $value) or
370 ($class_source eq $default_source);
371 push @authorised_values, $class_source;
372 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
376 #---- "true" authorised value
379 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
380 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value
}, $branch_limit ?
$branch_limit : () );
381 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
382 push @authorised_values, $value;
383 $authorised_lib{$value} = $lib;
387 $subfield_data{marc_value
} =CGI
::scrolling_list
( # FIXME: factor out scrolling_list
388 -name
=> "field_value",
389 -values => \
@authorised_values,
391 -labels
=> \
%authorised_lib,
396 -id
=> "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
397 -class => "input_marceditor",
399 # it's a thesaurus / authority field
401 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode
} ) {
402 $subfield_data{marc_value
} = "<input type=\"text\" $attributes />
403 <a href=\"#\" class=\"buttonDot\"
404 onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode
}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
406 # it's a plugin field
408 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder
} ) {
410 my $plugin = C4
::Context
->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
413 my $extended_param = plugin_parameters
( $dbh, $temp, $tagslib, $subfield_data{id
}, \
@loop_data );
414 my ( $function_name, $javascript ) = plugin_javascript
( $dbh, $temp, $tagslib, $subfield_data{id
}, \
@loop_data );
415 $subfield_data{marc_value
} = qq[<input type
="text" $attributes
416 onfocus
="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
417 onblur
=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
418 <a href
="#" class="buttonDot" onclick
="Clic$function_name('$subfield_data{id}'); return false;" title
="Tag Editor">...</a
>
421 warn "Plugin Failed: $plugin";
422 $subfield_data{marc_value
} = "<input type=\"text\" $attributes />"; # supply default input form
425 elsif ( $tag eq '' ) { # it's an hidden field
426 $subfield_data{marc_value
} = qq(<input type
="hidden" $attributes />);
428 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
429 $subfield_data{marc_value
} = qq(<input type
="text" $attributes />);
431 elsif ( length($value) > 100
432 or (C4
::Context
->preference("marcflavour") eq "UNIMARC" and
433 300 <= $tag && $tag < 400 && $subfield eq 'a' )
434 or (C4
::Context
->preference("marcflavour") eq "MARC21" and
435 500 <= $tag && $tag < 600 )
437 # oversize field (textarea)
438 $subfield_data{marc_value
} = "<textarea $attributes_no_value>$value</textarea>\n";
440 # it's a standard field
441 $subfield_data{marc_value
} = "<input type=\"text\" $attributes />";
443 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
444 push (@loop_data, \
%subfield_data);
447 } # -- End foreach tag
448 $authorised_values_sth->finish;
452 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
453 $template->param(item
=> \
@loop_data);
454 if (@notfoundbarcodes) {
455 my @notfoundbarcodesloop = map{{barcode
=>$_}}@notfoundbarcodes;
456 $template->param(notfoundbarcodes
=> \
@notfoundbarcodesloop);
459 } # -- End action="show"
461 $template->param(%$items_display_hashref) if $items_display_hashref;
465 $template->param( $op => 1 ) if $op;
467 if ($op eq "action") {
469 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
472 not_deleted_items
=> $not_deleted_items,
473 deleted_items
=> $deleted_items,
474 delete_records
=> $del_records,
475 deleted_records
=> $deleted_records,
476 not_deleted_loop
=> \
@not_deleted
480 foreach my $error (@errors) {
481 $template->param($error => 1) if $error;
483 $template->param(src
=> $src);
484 $template->param(biblionumber
=> $biblionumber);
485 output_html_with_http_headers
$input, $cookie, $template->output;
489 # ---------------- Functions
493 # now, build existiing item list
494 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
496 #---- finds where items.itemnumber is stored
497 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField
("items.itemnumber", "");
498 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField
("items.homebranch", "");
499 foreach my $itemnumber (@itemnumbers){
500 my $itemdata=GetItem
($itemnumber);
501 my $itemmarc=Item2Marc
($itemdata);
503 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
504 # loop through each subfield
505 my $itembranchcode=$field->subfield($branchtagsubfield);
506 if ($itembranchcode && C4
::Context
->preference("IndependentBranches")) {
508 my $userenv = C4
::Context
->userenv();
509 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
510 $this_row{'nomod'}=1;
513 my $tag=$field->tag();
514 foreach my $subfield ($field->subfields) {
515 my ($subfcode,$subfvalue)=@
$subfield;
516 next if ($tagslib->{$tag}->{$subfcode}->{tab
} ne 10
517 && $tag ne $itemtagfield
518 && $subfcode ne $itemtagsubfield);
520 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib
} if ($tagslib->{$tag}->{$subfcode}->{tab
} eq 10);
521 if ($tagslib->{$tag}->{$subfcode}->{tab
} eq 10) {
522 $this_row{$subfcode}=GetAuthorisedValueDesc
( $tag,
523 $subfcode, $subfvalue, '', $tagslib)
527 $this_row{itemnumber
} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
531 # grab title, author, and ISBN to identify bib that the item
532 # belongs to in the display
533 my $biblio=GetBiblioData
($$itemdata{biblionumber
});
534 $this_row{title
} = $biblio->{title
};
535 $this_row{author
} = $biblio->{author
};
536 $this_row{isbn
} = $biblio->{isbn
};
537 $this_row{biblionumber
} = $biblio->{biblionumber
};
540 push(@big_array, \
%this_row);
543 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
545 # now, construct template !
546 # First, the existing items for display
548 my @witnesscodessorted=sort keys %witness;
549 for my $row ( @big_array ) {
551 my @item_fields = map +{ field
=> $_ || '' }, @
$row{ @witnesscodessorted };
552 $row_data{item_value
} = [ @item_fields ];
553 $row_data{itemnumber
} = $row->{itemnumber
};
554 #reporting this_row values
555 $row_data{'nomod'} = $row->{'nomod'};
556 $row_data{bibinfo
} = $row->{bibinfo
};
557 $row_data{author
} = $row->{author
};
558 $row_data{title
} = $row->{title
};
559 $row_data{isbn
} = $row->{isbn
};
560 $row_data{biblionumber
} = $row->{biblionumber
};
561 my $is_on_loan = C4
::Circulation
::IsItemIssued
( $row->{itemnumber
} );
562 $row_data{onloan
} = $is_on_loan ?
1 : 0;
563 push(@item_value_loop,\
%row_data);
565 my @header_loop=map { { header_value
=> $witness{$_}} } @witnesscodessorted;
567 return { item_loop
=> \
@item_value_loop, item_header_loop
=> \
@header_loop };
570 #BE WARN : it is not the general case
571 # This function can be OK in the item marc record special case
572 # Where subfield is not repeated
573 # And where we are sure that field should correspond
576 my ($marcfrom,$marcto)=@_;
577 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField
("items.itemnumber", "");
578 my $fieldfrom=$marcfrom->field($itemtag);
579 my @fields_to=$marcto->field($itemtag);
581 foreach my $subfield ( $fieldfrom->subfields() ) {
582 foreach my $field_to_update ( @fields_to ) {
583 if ( $subfield->[1] ) {
584 unless ( $field_to_update->subfield($subfield->[0]) ~~ $subfield->[1] ) {
586 $field_to_update->update( $subfield->[0] => $subfield->[1] );
591 $field_to_update->delete_subfield( code
=> $subfield->[0] );
599 my ($tagfield,$insubfield,$record) = @_;
602 foreach my $field ($record->field($tagfield)) {
603 my @subfields = $field->subfields();
604 foreach my $subfield (@subfields) {
605 if (@
$subfield[0] eq $insubfield) {
606 $result .= @
$subfield[1];
607 $indicator = $field->indicator(1).$field->indicator(2);
611 return($indicator,$result);
614 # ----------------------------
615 # Background functions
618 sub add_results_to_template
{
619 my $template = shift;
621 $template->param(map { $_ => $results->{$_} } keys %{ $results });
624 sub add_saved_job_results_to_template
{
625 my $template = shift;
626 my $completedJobID = shift;
627 my $job = C4
::BackgroundJob
->fetch($sessionID, $completedJobID);
628 my $results = $job->results();
629 add_results_to_template
($template, $results);
631 my $fields = $job->get("modified_fields");
632 my $items = $job->get("modified_items");
634 modified_items
=> $items,
635 modified_fields
=> $fields,
639 sub put_in_background
{
640 my $job_size = shift;
642 my $job = C4
::BackgroundJob
->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
643 my $jobID = $job->id();
646 if (my $pid = fork) {
648 # return job ID as JSON
650 # prevent parent exiting from
651 # destroying the kid's database handle
652 # FIXME: according to DBI doc, this may not work for Oracle
653 $dbh->{InactiveDestroy
} = 1;
655 my $reply = CGI
->new("");
656 print $reply->header(-type
=> 'text/html');
657 print '{"jobID":"' . $jobID . '"}';
659 } elsif (defined $pid) {
661 # close STDOUT to signal to Apache that
662 # we're now running in the background
666 # fork failed, so exit immediately
667 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";