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');
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;
82 my $tagslib = &GetMarcStructure(1,$frameworkcode);
84 my $deleted_items = 0; # Number of deleted items
85 my $deleted_records = 0; # Number of deleted records ( with no items attached )
86 my $not_deleted_items = 0; # Number of items that could not be deleted
87 my @not_deleted; # List of the itemnumbers that could not be deleted
89 my %cookies = parse CGI::Cookie($cookie);
90 my $sessionID = $cookies{'CGISESSID'}->value;
93 #--- ----------------------------------------------------------------------------
94 if ($op eq "action") {
95 #-------------------------------------------------------------------------------
96 my @tags = $input->param('tag');
97 my @subfields = $input->param('subfield');
98 my @values = $input->param('field_value');
99 my @disabled = $input->param('disable_input');
100 # build indicator hash.
101 my @ind_tag = $input->param('ind_tag');
102 my @indicator = $input->param('indicator');
104 # Is there something to modify ?
105 # TODO : We shall use this var to warn the user in case no modification was done to the items
106 my $values_to_modify = scalar(grep {!/^$/} @values);
107 my $values_to_blank = scalar(@disabled);
110 # Once the job is done
111 if ($completedJobID) {
112 # If we have a reasonable amount of items, we display them
113 if (scalar(@itemnumbers) <= 1000) {
114 $items_display_hashref=BuildItemsData(@itemnumbers);
116 # Else, we only display the barcode
117 my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
118 $template->param("simple_items_display" => \@simple_items_display);
121 # Setting the job as done
122 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
124 # Calling the template
125 add_saved_job_results_to_template($template, $completedJobID);
128 # While the job is getting done
130 # Job size is the number of items we have to process
131 my $job_size = scalar(@itemnumbers);
134 # If we asked for background processing
135 if ($runinbackground) {
136 $job = put_in_background($job_size);
139 #initializing values for updates
140 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
141 if ($values_to_modify){
142 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);
164 if ($input->param("del")){
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);
190 UpdateMarcWith( $marcitem, $localmarcitem );
192 if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
193 LostItem($itemnumber, 'MARK RETURNED', 'CHARGE FEE') if $item->{itemlost};
203 #-------------------------------------------------------------------------------
204 # build screen with existing items. and "new" one
205 #-------------------------------------------------------------------------------
208 my $filefh = $input->upload('uploadfile');
209 my $filecontent = $input->param('filecontent');
210 my @notfoundbarcodes;
214 while (my $content=<$filefh>){
215 $content =~ s/[\r\n]*$//;
216 push @contentlist, $content if $content;
219 if ($filecontent eq 'barcode_file') {
220 foreach my $barcode (@contentlist) {
222 my $itemnumber = GetItemnumberFromBarcode($barcode);
224 push @itemnumbers,$itemnumber;
226 push @notfoundbarcodes, $barcode;
230 elsif ( $filecontent eq 'itemid_file') {
231 @itemnumbers = @contentlist;
234 if (defined $biblionumber){
235 my @all_items = GetItemsInfo( $biblionumber );
236 foreach my $itm (@all_items) {
237 push @itemnumbers, $itm->{itemnumber};
240 if ( my $list=$input->param('barcodelist')){
241 push my @barcodelist, uniq( split(/\s\n/, $list) );
243 foreach my $barcode (@barcodelist) {
245 my $itemnumber = GetItemnumberFromBarcode($barcode);
247 push @itemnumbers,$itemnumber;
249 push @notfoundbarcodes, $barcode;
256 # Flag to tell the template there are valid results, hidden or not
257 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
258 # Only display the items if there are no more than 1000
259 if (scalar(@itemnumbers) <= 1000) {
260 $items_display_hashref=BuildItemsData(@itemnumbers);
262 $template->param("too_many_items" => scalar(@itemnumbers));
263 # Even if we do not display the items, we need the itemnumbers
264 my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
265 $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
267 # now, build the item form for entering a new item
270 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
272 my $branches = GetBranchesLoop(); # build once ahead of time, instead of multiple times later.
274 # Adding a default choice, in case the user does not want to modify the branch
275 my $nochange_branch = { branchname => '', value => '', selected => 1 };
276 unshift (@$branches, $nochange_branch);
278 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
281 foreach my $tag (sort keys %{$tagslib}) {
282 # loop through each subfield
283 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
284 next if subfield_is_koha_internal_p($subfield);
285 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
286 # barcode and stocknumber are not meant to be batch-modified
287 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
288 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
291 my $index_subfield = int(rand(1000000));
292 if ($subfield eq '@'){
293 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
295 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
297 $subfield_data{tag} = $tag;
298 $subfield_data{subfield} = $subfield;
299 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
300 # $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
301 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
302 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
303 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
305 $value =~ s/"/"/g;
307 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
308 # get today date & replace YYYY, MM, DD if provided in the default value
309 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
310 $value =~ s/YYYY/$year/g;
311 $value =~ s/MM/$month/g;
312 $value =~ s/DD/$day/g;
314 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
315 # testing branch value if IndependantBranches.
317 my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
318 my $attributes = qq($attributes_no_value value="$value" );
320 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
321 my @authorised_values;
323 # builds list, depending on authorised value...
325 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
326 foreach my $thisbranch (@$branches) {
327 push @authorised_values, $thisbranch->{value};
328 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
332 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
333 push @authorised_values, "";
334 my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
336 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
337 push @authorised_values, $itemtype;
338 $authorised_lib{$itemtype} = $description;
344 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
345 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
347 my $class_sources = GetClassSources();
348 my $default_source = C4::Context->preference("DefaultClassificationSource");
350 foreach my $class_source (sort keys %$class_sources) {
351 next unless $class_sources->{$class_source}->{'used'} or
352 ($value and $class_source eq $value) or
353 ($class_source eq $default_source);
354 push @authorised_values, $class_source;
355 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
359 #---- "true" authorised value
362 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
363 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
364 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
365 push @authorised_values, $value;
366 $authorised_lib{$value} = $lib;
370 $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
371 -name => "field_value",
372 -values => \@authorised_values,
374 -labels => \%authorised_lib,
379 -id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
380 -class => "input_marceditor",
382 # it's a thesaurus / authority field
384 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
385 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
386 <a href=\"#\" class=\"buttonDot\"
387 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>
389 # it's a plugin field
391 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
393 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
396 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
397 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
398 $subfield_data{marc_value} = qq[<input type="text" $attributes
399 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
400 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
401 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
404 warn "Plugin Failed: $plugin";
405 $subfield_data{marc_value} = "<input type=\"text\" $attributes />"; # supply default input form
408 elsif ( $tag eq '' ) { # it's an hidden field
409 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
411 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
412 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
414 elsif ( length($value) > 100
415 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
416 300 <= $tag && $tag < 400 && $subfield eq 'a' )
417 or (C4::Context->preference("marcflavour") eq "MARC21" and
418 500 <= $tag && $tag < 600 )
420 # oversize field (textarea)
421 $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
423 # it's a standard field
424 $subfield_data{marc_value} = "<input type=\"text\" $attributes />";
426 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
427 push (@loop_data, \%subfield_data);
430 } # -- End foreach tag
433 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
434 $template->param(item => \@loop_data);
435 if (@notfoundbarcodes) {
436 my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
437 $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
440 } # -- End action="show"
442 $template->param(%$items_display_hashref) if $items_display_hashref;
446 $template->param( $op => 1 ) if $op;
448 if ($op eq "action") {
450 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
453 not_deleted_items => $not_deleted_items,
454 deleted_items => $deleted_items,
455 delete_records => $del_records,
456 deleted_records => $deleted_records,
457 not_deleted_loop => \@not_deleted
461 foreach my $error (@errors) {
462 $template->param($error => 1) if $error;
464 $template->param(src => $src);
465 $template->param(biblionumber => $biblionumber);
466 output_html_with_http_headers $input, $cookie, $template->output;
470 # ---------------- Functions
474 # now, build existiing item list
475 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
477 #---- finds where items.itemnumber is stored
478 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
479 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
480 foreach my $itemnumber (@itemnumbers){
481 my $itemdata=GetItem($itemnumber);
482 my $itemmarc=Item2Marc($itemdata);
484 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
485 # loop through each subfield
486 my $itembranchcode=$field->subfield($branchtagsubfield);
487 if ($itembranchcode && C4::Context->preference("IndependantBranches")) {
489 my $userenv = C4::Context->userenv();
490 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
491 $this_row{'nomod'}=1;
494 my $tag=$field->tag();
495 foreach my $subfield ($field->subfields) {
496 my ($subfcode,$subfvalue)=@$subfield;
497 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
498 && $tag ne $itemtagfield
499 && $subfcode ne $itemtagsubfield);
501 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
502 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
503 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
504 $subfcode, $subfvalue, '', $tagslib)
508 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
512 # grab title, author, and ISBN to identify bib that the item
513 # belongs to in the display
514 my $biblio=GetBiblioData($$itemdata{biblionumber});
515 $this_row{title} = $biblio->{title};
516 $this_row{author} = $biblio->{author};
517 $this_row{isbn} = $biblio->{isbn};
518 $this_row{biblionumber} = $biblio->{biblionumber};
521 push(@big_array, \%this_row);
524 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
526 # now, construct template !
527 # First, the existing items for display
529 my @witnesscodessorted=sort keys %witness;
530 for my $row ( @big_array ) {
532 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
533 $row_data{item_value} = [ @item_fields ];
534 $row_data{itemnumber} = $row->{itemnumber};
535 #reporting this_row values
536 $row_data{'nomod'} = $row->{'nomod'};
537 $row_data{bibinfo} = $row->{bibinfo};
538 $row_data{author} = $row->{author};
539 $row_data{title} = $row->{title};
540 $row_data{isbn} = $row->{isbn};
541 $row_data{biblionumber} = $row->{biblionumber};
542 push(@item_value_loop,\%row_data);
544 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
546 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
549 #BE WARN : it is not the general case
550 # This function can be OK in the item marc record special case
551 # Where subfield is not repeated
552 # And where we are sure that field should correspond
555 my ($marcfrom,$marcto)=@_;
556 #warn "FROM :",$marcfrom->as_formatted;
557 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
558 my $fieldfrom=$marcfrom->field($itemtag);
559 my @fields_to=$marcto->field($itemtag);
560 foreach my $subfield ($fieldfrom->subfields()){
561 foreach my $field_to_update (@fields_to){
563 $field_to_update->update($subfield->[0]=>$subfield->[1]);
566 $field_to_update->delete_subfield(code=> $subfield->[0]);
570 #warn "TO edited:",$marcto->as_formatted;
574 my ($tagfield,$insubfield,$record) = @_;
577 foreach my $field ($record->field($tagfield)) {
578 my @subfields = $field->subfields();
579 foreach my $subfield (@subfields) {
580 if (@$subfield[0] eq $insubfield) {
581 $result .= @$subfield[1];
582 $indicator = $field->indicator(1).$field->indicator(2);
586 return($indicator,$result);
589 # ----------------------------
590 # Background functions
593 sub add_results_to_template {
594 my $template = shift;
596 $template->param(map { $_ => $results->{$_} } keys %{ $results });
599 sub add_saved_job_results_to_template {
600 my $template = shift;
601 my $completedJobID = shift;
602 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
603 my $results = $job->results();
604 add_results_to_template($template, $results);
607 sub put_in_background {
608 my $job_size = shift;
610 my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
611 my $jobID = $job->id();
614 if (my $pid = fork) {
616 # return job ID as JSON
618 # prevent parent exiting from
619 # destroying the kid's database handle
620 # FIXME: according to DBI doc, this may not work for Oracle
621 $dbh->{InactiveDestroy} = 1;
623 my $reply = CGI->new("");
624 print $reply->header(-type => 'text/html');
625 print '{"jobID":"' . $jobID . '"}';
627 } elsif (defined $pid) {
629 # close STDOUT to signal to Apache that
630 # we're now running in the background
634 # fork failed, so exit immediately
635 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";