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;
39 my $dbh = C4::Context->dbh;
40 my $error = $input->param('error');
41 my @itemnumbers = $input->param('itemnumber');
42 my $biblionumber = $input->param('biblionumber');
43 my $op = $input->param('op');
44 my $del = $input->param('del');
45 my $del_records = $input->param('del_records');
46 my $completedJobID = $input->param('completedJobID');
47 my $runinbackground = $input->param('runinbackground');
48 my $src = $input->param('src');
54 $template_name = "tools/batchMod.tmpl";
55 $template_flag = { tools => '*' };
58 $template_name = ($del) ? "tools/batchMod-del.tmpl" : "tools/batchMod-edit.tmpl";
59 $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' };
63 my ($template, $loggedinuser, $cookie)
64 = get_template_and_user({template_name => $template_name,
68 flagsrequired => $template_flag,
72 my $today_iso = C4::Dates->today('iso');
73 $template->param(today_iso => $today_iso);
74 $template->param(del => $del);
78 my @errors; # store errors found while checking data BEFORE saving item.
79 my $items_display_hashref;
81 my $tagslib = &GetMarcStructure(1,$frameworkcode);
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
88 my %cookies = parse CGI::Cookie($cookie);
89 my $sessionID = $cookies{'CGISESSID'}->value;
92 #--- ----------------------------------------------------------------------------
93 if ($op eq "action") {
94 #-------------------------------------------------------------------------------
95 my @tags = $input->param('tag');
96 my @subfields = $input->param('subfield');
97 my @values = $input->param('field_value');
98 my @disabled = $input->param('disable_input');
99 # build indicator hash.
100 my @ind_tag = $input->param('ind_tag');
101 my @indicator = $input->param('indicator');
103 # Is there something to modify ?
104 # TODO : We shall use this var to warn the user in case no modification was done to the items
105 my $values_to_modify = scalar(grep {!/^$/} @values);
106 my $values_to_blank = scalar(@disabled);
109 # Once the job is done
110 if ($completedJobID) {
111 # If we have a reasonable amount of items, we display them
112 if (scalar(@itemnumbers) <= 1000) {
113 $items_display_hashref=BuildItemsData(@itemnumbers);
115 # Else, we only display the barcode
116 my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
117 $template->param("simple_items_display" => \@simple_items_display);
120 # Setting the job as done
121 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
123 # Calling the template
124 add_saved_job_results_to_template($template, $completedJobID);
127 # While the job is getting done
129 # Job size is the number of items we have to process
130 my $job_size = scalar(@itemnumbers);
133 # If we asked for background processing
134 if ($runinbackground) {
135 $job = put_in_background($job_size);
138 #initializing values for updates
139 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
140 if ($values_to_modify){
141 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
143 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
145 if ($values_to_blank){
146 foreach my $disabledsubf (@disabled){
147 if ($marcitem && $marcitem->field($itemtagfield)){
148 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
151 $marcitem = MARC::Record->new();
152 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
159 foreach my $itemnumber(@itemnumbers){
161 $job->progress($i) if $runinbackground;
162 my $itemdata = GetItem($itemnumber);
163 if ($input->param("del")){
164 my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
168 $not_deleted_items++;
170 { biblionumber => $itemdata->{'biblionumber'},
171 itemnumber => $itemdata->{'itemnumber'},
172 barcode => $itemdata->{'barcode'},
173 title => $itemdata->{'title'},
178 # If there are no items left, delete the biblio
179 if ( $del_records ) {
180 my $itemscount = GetItemsCount($itemdata->{'biblionumber'});
181 if ( $itemscount == 0 ) {
182 my $error = DelBiblio($itemdata->{'biblionumber'});
183 $deleted_records++ unless ( $error );
187 if ($values_to_modify || $values_to_blank) {
188 my $localmarcitem = Item2Marc($itemdata);
189 UpdateMarcWith( $marcitem, $localmarcitem );
191 if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
192 LostItem($itemnumber, 'MARK RETURNED', 'CHARGE FEE') if $item->{itemlost};
202 #-------------------------------------------------------------------------------
203 # build screen with existing items. and "new" one
204 #-------------------------------------------------------------------------------
207 my $filefh = $input->upload('uploadfile');
208 my $filecontent = $input->param('filecontent');
209 my @notfoundbarcodes;
213 while (my $content=<$filefh>){
214 $content =~ s/[\r\n]*$//;
215 push @contentlist, $content if $content;
218 if ($filecontent eq 'barcode_file') {
219 foreach my $barcode (@contentlist) {
221 my $itemnumber = GetItemnumberFromBarcode($barcode);
223 push @itemnumbers,$itemnumber;
225 push @notfoundbarcodes, $barcode;
229 elsif ( $filecontent eq 'itemid_file') {
230 @itemnumbers = @contentlist;
233 if (defined $biblionumber){
234 my @all_items = GetItemsInfo( $biblionumber );
235 foreach my $itm (@all_items) {
236 push @itemnumbers, $itm->{itemnumber};
239 if ( my $list=$input->param('barcodelist')){
240 push my @barcodelist, split(/\s\n/, $list);
242 foreach my $barcode (@barcodelist) {
244 my $itemnumber = GetItemnumberFromBarcode($barcode);
246 push @itemnumbers,$itemnumber;
248 push @notfoundbarcodes, $barcode;
255 # Flag to tell the template there are valid results, hidden or not
256 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
257 # Only display the items if there are no more than 1000
258 if (scalar(@itemnumbers) <= 1000) {
259 $items_display_hashref=BuildItemsData(@itemnumbers);
261 $template->param("too_many_items" => scalar(@itemnumbers));
262 # Even if we do not display the items, we need the itemnumbers
263 my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
264 $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
266 # now, build the item form for entering a new item
269 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
270 my $query = qq{SELECT authorised_value, lib FROM authorised_values};
271 $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id ) } if $branch_limit;
272 $query .= qq{ WHERE category = ?};
273 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL ) } if $branch_limit;
274 $query .= qq{ GROUP BY lib ORDER BY lib, lib_opac};
275 my $authorised_values_sth = $dbh->prepare( $query );
277 my $branches = GetBranchesLoop(); # build once ahead of time, instead of multiple times later.
279 # Adding a default choice, in case the user does not want to modify the branch
280 my $nochange_branch = { branchname => '', value => '', selected => 1 };
281 unshift (@$branches, $nochange_branch);
283 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
286 foreach my $tag (sort keys %{$tagslib}) {
287 # loop through each subfield
288 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
289 next if subfield_is_koha_internal_p($subfield);
290 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
291 # barcode and stocknumber are not meant to be batch-modified
292 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
293 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
296 my $index_subfield = int(rand(1000000));
297 if ($subfield eq '@'){
298 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
300 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
302 $subfield_data{tag} = $tag;
303 $subfield_data{subfield} = $subfield;
304 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
305 # $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
306 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
307 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
308 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
310 $value =~ s/"/"/g;
312 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
313 # get today date & replace YYYY, MM, DD if provided in the default value
314 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
315 $value =~ s/YYYY/$year/g;
316 $value =~ s/MM/$month/g;
317 $value =~ s/DD/$day/g;
319 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
320 # testing branch value if IndependantBranches.
322 my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
323 my $attributes = qq($attributes_no_value value="$value" );
325 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
326 my @authorised_values;
328 # builds list, depending on authorised value...
330 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
331 foreach my $thisbranch (@$branches) {
332 push @authorised_values, $thisbranch->{value};
333 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
337 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
338 push @authorised_values, "";
339 my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
341 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
342 push @authorised_values, $itemtype;
343 $authorised_lib{$itemtype} = $description;
349 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
350 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
352 my $class_sources = GetClassSources();
353 my $default_source = C4::Context->preference("DefaultClassificationSource");
355 foreach my $class_source (sort keys %$class_sources) {
356 next unless $class_sources->{$class_source}->{'used'} or
357 ($value and $class_source eq $value) or
358 ($class_source eq $default_source);
359 push @authorised_values, $class_source;
360 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
364 #---- "true" authorised value
367 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
368 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value}, $branch_limit ? $branch_limit : () );
369 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
370 push @authorised_values, $value;
371 $authorised_lib{$value} = $lib;
375 $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
376 -name => "field_value",
377 -values => \@authorised_values,
379 -labels => \%authorised_lib,
384 -id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
385 -class => "input_marceditor",
387 # it's a thesaurus / authority field
389 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
390 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
391 <a href=\"#\" class=\"buttonDot\"
392 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>
394 # it's a plugin field
396 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
398 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
401 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
402 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
403 $subfield_data{marc_value} = qq[<input type="text" $attributes
404 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
405 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
406 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
409 warn "Plugin Failed: $plugin";
410 $subfield_data{marc_value} = "<input type=\"text\" $attributes />"; # supply default input form
413 elsif ( $tag eq '' ) { # it's an hidden field
414 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
416 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
417 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
419 elsif ( length($value) > 100
420 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
421 300 <= $tag && $tag < 400 && $subfield eq 'a' )
422 or (C4::Context->preference("marcflavour") eq "MARC21" and
423 500 <= $tag && $tag < 600 )
425 # oversize field (textarea)
426 $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
428 # it's a standard field
429 $subfield_data{marc_value} = "<input type=\"text\" $attributes />";
431 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
432 push (@loop_data, \%subfield_data);
435 } # -- End foreach tag
436 $authorised_values_sth->finish;
440 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
441 $template->param(item => \@loop_data);
442 if (@notfoundbarcodes) {
443 my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
444 $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
447 } # -- End action="show"
449 $template->param(%$items_display_hashref) if $items_display_hashref;
453 $template->param( $op => 1 ) if $op;
455 if ($op eq "action") {
457 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
460 not_deleted_items => $not_deleted_items,
461 deleted_items => $deleted_items,
462 delete_records => $del_records,
463 deleted_records => $deleted_records,
464 not_deleted_loop => \@not_deleted
468 foreach my $error (@errors) {
469 $template->param($error => 1) if $error;
471 $template->param(src => $src);
472 $template->param(biblionumber => $biblionumber);
473 output_html_with_http_headers $input, $cookie, $template->output;
477 # ---------------- Functions
481 # now, build existiing item list
482 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
484 #---- finds where items.itemnumber is stored
485 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
486 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
487 foreach my $itemnumber (@itemnumbers){
488 my $itemdata=GetItem($itemnumber);
489 my $itemmarc=Item2Marc($itemdata);
491 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
492 # loop through each subfield
493 my $itembranchcode=$field->subfield($branchtagsubfield);
494 if ($itembranchcode && C4::Context->preference("IndependantBranches")) {
496 my $userenv = C4::Context->userenv();
497 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
498 $this_row{'nomod'}=1;
501 my $tag=$field->tag();
502 foreach my $subfield ($field->subfields) {
503 my ($subfcode,$subfvalue)=@$subfield;
504 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
505 && $tag ne $itemtagfield
506 && $subfcode ne $itemtagsubfield);
508 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
509 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
510 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
511 $subfcode, $subfvalue, '', $tagslib)
515 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
519 # grab title, author, and ISBN to identify bib that the item
520 # belongs to in the display
521 my $biblio=GetBiblioData($$itemdata{biblionumber});
522 $this_row{title} = $biblio->{title};
523 $this_row{author} = $biblio->{author};
524 $this_row{isbn} = $biblio->{isbn};
525 $this_row{biblionumber} = $biblio->{biblionumber};
528 push(@big_array, \%this_row);
531 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
533 # now, construct template !
534 # First, the existing items for display
536 my @witnesscodessorted=sort keys %witness;
537 for my $row ( @big_array ) {
539 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
540 $row_data{item_value} = [ @item_fields ];
541 $row_data{itemnumber} = $row->{itemnumber};
542 #reporting this_row values
543 $row_data{'nomod'} = $row->{'nomod'};
544 $row_data{bibinfo} = $row->{bibinfo};
545 $row_data{author} = $row->{author};
546 $row_data{title} = $row->{title};
547 $row_data{isbn} = $row->{isbn};
548 $row_data{biblionumber} = $row->{biblionumber};
549 push(@item_value_loop,\%row_data);
551 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
553 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
556 #BE WARN : it is not the general case
557 # This function can be OK in the item marc record special case
558 # Where subfield is not repeated
559 # And where we are sure that field should correspond
562 my ($marcfrom,$marcto)=@_;
563 #warn "FROM :",$marcfrom->as_formatted;
564 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
565 my $fieldfrom=$marcfrom->field($itemtag);
566 my @fields_to=$marcto->field($itemtag);
567 foreach my $subfield ($fieldfrom->subfields()){
568 foreach my $field_to_update (@fields_to){
570 $field_to_update->update($subfield->[0]=>$subfield->[1]);
573 $field_to_update->delete_subfield(code=> $subfield->[0]);
577 #warn "TO edited:",$marcto->as_formatted;
581 my ($tagfield,$insubfield,$record) = @_;
584 foreach my $field ($record->field($tagfield)) {
585 my @subfields = $field->subfields();
586 foreach my $subfield (@subfields) {
587 if (@$subfield[0] eq $insubfield) {
588 $result .= @$subfield[1];
589 $indicator = $field->indicator(1).$field->indicator(2);
593 return($indicator,$result);
596 # ----------------------------
597 # Background functions
600 sub add_results_to_template {
601 my $template = shift;
603 $template->param(map { $_ => $results->{$_} } keys %{ $results });
606 sub add_saved_job_results_to_template {
607 my $template = shift;
608 my $completedJobID = shift;
609 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
610 my $results = $job->results();
611 add_results_to_template($template, $results);
614 sub put_in_background {
615 my $job_size = shift;
617 my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
618 my $jobID = $job->id();
621 if (my $pid = fork) {
623 # return job ID as JSON
625 # prevent parent exiting from
626 # destroying the kid's database handle
627 # FIXME: according to DBI doc, this may not work for Oracle
628 $dbh->{InactiveDestroy} = 1;
630 my $reply = CGI->new("");
631 print $reply->header(-type => 'text/html');
632 print '{"jobID":"' . $jobID . '"}';
634 } elsif (defined $pid) {
636 # close STDOUT to signal to Apache that
637 # we're now running in the background
641 # fork failed, so exit immediately
642 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";