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 $op = $input->param('op');
43 my $del = $input->param('del');
44 my $completedJobID = $input->param('completedJobID');
45 my $runinbackground = $input->param('runinbackground');
51 $template_name = "tools/batchMod.tmpl";
52 $template_flag = { tools => '*' };
54 $template_name = ($del) ? "tools/batchMod-del.tmpl" : "tools/batchMod-edit.tmpl";
55 $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' };
59 my ($template, $loggedinuser, $cookie)
60 = get_template_and_user({template_name => $template_name,
64 flagsrequired => $template_flag,
68 my $today_iso = C4::Dates->today('iso');
69 $template->param(today_iso => $today_iso);
70 $template->param(del => $del);
74 my @errors; # store errors found while checking data BEFORE saving item.
75 my $items_display_hashref;
77 my $tagslib = &GetMarcStructure(1,$frameworkcode);
79 my $deleted_items = 0; # Numbers of deleted items
80 my $not_deleted_items = 0; # Numbers of items that could not be deleted
81 my @not_deleted; # List of the itemnumbers that could not be deleted
83 my %cookies = parse CGI::Cookie($cookie);
84 my $sessionID = $cookies{'CGISESSID'}->value;
87 #--- ----------------------------------------------------------------------------
88 if ($op eq "action") {
89 #-------------------------------------------------------------------------------
90 my @tags = $input->param('tag');
91 my @subfields = $input->param('subfield');
92 my @values = $input->param('field_value');
93 my @disabled = $input->param('disable_input');
94 # build indicator hash.
95 my @ind_tag = $input->param('ind_tag');
96 my @indicator = $input->param('indicator');
98 # Is there something to modify ?
99 # TODO : We shall use this var to warn the user in case no modification was done to the items
100 my $values_to_modify = scalar(grep {!/^$/} @values);
101 my $values_to_blank = scalar(@disabled);
104 # Once the job is done
105 if ($completedJobID) {
106 # If we have a reasonable amount of items, we display them
107 if (scalar(@itemnumbers) <= 1000) {
108 $items_display_hashref=BuildItemsData(@itemnumbers);
110 # Else, we only display the barcode
111 my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
112 $template->param("simple_items_display" => \@simple_items_display);
115 # Setting the job as done
116 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
118 # Calling the template
119 add_saved_job_results_to_template($template, $completedJobID);
122 # While the job is getting done
124 # Job size is the number of items we have to process
125 my $job_size = scalar(@itemnumbers);
127 my $callback = sub {};
129 # If we asked for background processing
130 if ($runinbackground) {
131 $job = put_in_background($job_size);
132 $callback = progress_callback($job, $dbh);
135 #initializing values for updates
136 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
137 if ($values_to_modify){
138 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
140 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
142 if ($values_to_blank){
143 foreach my $disabledsubf (@disabled){
144 if ($marcitem && $marcitem->field($itemtagfield)){
145 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
148 $marcitem = MARC::Record->new();
149 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
156 foreach my $itemnumber(@itemnumbers){
158 $job->progress($i) if $runinbackground;
159 my $itemdata=GetItem($itemnumber);
160 if ($input->param("del")){
161 my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
165 $not_deleted_items++;
167 { biblionumber => $itemdata->{'biblionumber'},
168 itemnumber => $itemdata->{'itemnumber'},
169 barcode => $itemdata->{'barcode'},
170 title => $itemdata->{'title'},
175 if ($values_to_modify || $values_to_blank) {
176 my $localmarcitem = Item2Marc($itemdata);
177 UpdateMarcWith( $marcitem, $localmarcitem );
179 if ( my $item = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) ) {
180 LostItem($itemnumber, 'MARK RETURNED', 'CHARGE FEE') if $item->{itemlost};
190 #-------------------------------------------------------------------------------
191 # build screen with existing items. and "new" one
192 #-------------------------------------------------------------------------------
195 my $filefh = $input->upload('uploadfile');
196 my $filecontent = $input->param('filecontent');
197 my @notfoundbarcodes;
201 while (my $content=<$filefh>){
202 $content =~ s/[\r\n]*$//;
203 push @contentlist, $content if $content;
206 if ($filecontent eq 'barcode_file') {
207 foreach my $barcode (@contentlist) {
209 my $itemnumber = GetItemnumberFromBarcode($barcode);
211 push @itemnumbers,$itemnumber;
213 push @notfoundbarcodes, $barcode;
217 elsif ( $filecontent eq 'itemid_file') {
218 @itemnumbers = @contentlist;
221 if ( my $list=$input->param('barcodelist')){
222 push my @barcodelist, split(/\s\n/, $list);
224 foreach my $barcode (@barcodelist) {
226 my $itemnumber = GetItemnumberFromBarcode($barcode);
228 push @itemnumbers,$itemnumber;
230 push @notfoundbarcodes, $barcode;
237 # Flag to tell the template there are valid results, hidden or not
238 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
239 # Only display the items if there are no more than 1000
240 if (scalar(@itemnumbers) <= 1000) {
241 $items_display_hashref=BuildItemsData(@itemnumbers);
243 $template->param("too_many_items" => scalar(@itemnumbers));
244 # Even if we do not display the items, we need the itemnumbers
245 my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
246 $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
248 # now, build the item form for entering a new item
251 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
253 my $branches = GetBranchesLoop(); # build once ahead of time, instead of multiple times later.
255 # Adding a default choice, in case the user does not want to modify the branch
256 my $nochange_branch = { branchname => '', value => '', selected => 1 };
257 unshift (@$branches, $nochange_branch);
259 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
262 foreach my $tag (sort keys %{$tagslib}) {
263 # loop through each subfield
264 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
265 next if subfield_is_koha_internal_p($subfield);
266 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
267 # barcode and stocknumber are not meant to be batch-modified
268 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
269 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
272 my $index_subfield = int(rand(1000000));
273 if ($subfield eq '@'){
274 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
276 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
278 $subfield_data{tag} = $tag;
279 $subfield_data{subfield} = $subfield;
280 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
281 # $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
282 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
283 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
284 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
286 $value =~ s/"/"/g;
288 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
289 # get today date & replace YYYY, MM, DD if provided in the default value
290 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
291 $value =~ s/YYYY/$year/g;
292 $value =~ s/MM/$month/g;
293 $value =~ s/DD/$day/g;
295 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
296 # testing branch value if IndependantBranches.
298 my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
299 my $attributes = qq($attributes_no_value value="$value" );
301 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
302 my @authorised_values;
304 # builds list, depending on authorised value...
306 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
307 foreach my $thisbranch (@$branches) {
308 push @authorised_values, $thisbranch->{value};
309 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
313 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
314 push @authorised_values, "";
315 my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
317 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
318 push @authorised_values, $itemtype;
319 $authorised_lib{$itemtype} = $description;
325 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
326 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
328 my $class_sources = GetClassSources();
329 my $default_source = C4::Context->preference("DefaultClassificationSource");
331 foreach my $class_source (sort keys %$class_sources) {
332 next unless $class_sources->{$class_source}->{'used'} or
333 ($value and $class_source eq $value) or
334 ($class_source eq $default_source);
335 push @authorised_values, $class_source;
336 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
340 #---- "true" authorised value
343 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
344 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
345 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
346 push @authorised_values, $value;
347 $authorised_lib{$value} = $lib;
351 $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
352 -name => "field_value",
353 -values => \@authorised_values,
355 -labels => \%authorised_lib,
360 -id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
361 -class => "input_marceditor",
363 # it's a thesaurus / authority field
365 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
366 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
367 <a href=\"#\" class=\"buttonDot\"
368 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>
370 # it's a plugin field
372 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
374 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
377 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
378 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
379 $subfield_data{marc_value} = qq[<input $attributes
380 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
381 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
382 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
385 warn "Plugin Failed: $plugin";
386 $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
389 elsif ( $tag eq '' ) { # it's an hidden field
390 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
392 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
393 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
395 elsif ( length($value) > 100
396 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
397 300 <= $tag && $tag < 400 && $subfield eq 'a' )
398 or (C4::Context->preference("marcflavour") eq "MARC21" and
399 500 <= $tag && $tag < 600 )
401 # oversize field (textarea)
402 $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
404 # it's a standard field
405 $subfield_data{marc_value} = "<input $attributes />";
407 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
408 push (@loop_data, \%subfield_data);
411 } # -- End foreach tag
414 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
415 $template->param(item => \@loop_data);
416 if (@notfoundbarcodes) {
417 my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
418 $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
421 } # -- End action="show"
423 $template->param(%$items_display_hashref) if $items_display_hashref;
429 if ($op eq "action") {
431 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
434 not_deleted_items => $not_deleted_items,
435 deleted_items => $deleted_items,
436 not_deleted_loop => \@not_deleted
440 foreach my $error (@errors) {
441 $template->param($error => 1);
443 output_html_with_http_headers $input, $cookie, $template->output;
447 # ---------------- Functions
451 # now, build existiing item list
452 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
454 #---- finds where items.itemnumber is stored
455 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
456 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
457 foreach my $itemnumber (@itemnumbers){
458 my $itemdata=GetItem($itemnumber);
459 my $itemmarc=Item2Marc($itemdata);
461 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
462 # loop through each subfield
463 my $itembranchcode=$field->subfield($branchtagsubfield);
464 if ($itembranchcode && C4::Context->preference("IndependantBranches")) {
466 my $userenv = C4::Context->userenv();
467 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
468 $this_row{'nomod'}=1;
471 my $tag=$field->tag();
472 foreach my $subfield ($field->subfields) {
473 my ($subfcode,$subfvalue)=@$subfield;
474 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
475 && $tag ne $itemtagfield
476 && $subfcode ne $itemtagsubfield);
478 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
479 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
480 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
481 $subfcode, $subfvalue, '', $tagslib)
485 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
489 # grab title, author, and ISBN to identify bib that the item
490 # belongs to in the display
491 my $biblio=GetBiblioData($$itemdata{biblionumber});
492 $this_row{title} = $biblio->{title};
493 $this_row{author} = $biblio->{author};
494 $this_row{isbn} = $biblio->{isbn};
495 $this_row{biblionumber} = $biblio->{biblionumber};
498 push(@big_array, \%this_row);
501 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
503 # now, construct template !
504 # First, the existing items for display
506 my @witnesscodessorted=sort keys %witness;
507 for my $row ( @big_array ) {
509 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
510 $row_data{item_value} = [ @item_fields ];
511 $row_data{itemnumber} = $row->{itemnumber};
512 #reporting this_row values
513 $row_data{'nomod'} = $row->{'nomod'};
514 $row_data{bibinfo} = $row->{bibinfo};
515 $row_data{author} = $row->{author};
516 $row_data{title} = $row->{title};
517 $row_data{isbn} = $row->{isbn};
518 $row_data{biblionumber} = $row->{biblionumber};
519 push(@item_value_loop,\%row_data);
521 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
523 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
526 #BE WARN : it is not the general case
527 # This function can be OK in the item marc record special case
528 # Where subfield is not repeated
529 # And where we are sure that field should correspond
532 my ($marcfrom,$marcto)=@_;
533 #warn "FROM :",$marcfrom->as_formatted;
534 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
535 my $fieldfrom=$marcfrom->field($itemtag);
536 my @fields_to=$marcto->field($itemtag);
537 foreach my $subfield ($fieldfrom->subfields()){
538 foreach my $field_to_update (@fields_to){
540 $field_to_update->update($subfield->[0]=>$subfield->[1]);
543 $field_to_update->delete_subfield(code=> $subfield->[0]);
547 #warn "TO edited:",$marcto->as_formatted;
551 my ($tagfield,$insubfield,$record) = @_;
554 foreach my $field ($record->field($tagfield)) {
555 my @subfields = $field->subfields();
556 foreach my $subfield (@subfields) {
557 if (@$subfield[0] eq $insubfield) {
558 $result .= @$subfield[1];
559 $indicator = $field->indicator(1).$field->indicator(2);
563 return($indicator,$result);
566 # ----------------------------
567 # Background functions
570 sub add_results_to_template {
571 my $template = shift;
573 $template->param(map { $_ => $results->{$_} } keys %{ $results });
576 sub add_saved_job_results_to_template {
577 my $template = shift;
578 my $completedJobID = shift;
579 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
580 my $results = $job->results();
581 add_results_to_template($template, $results);
584 sub put_in_background {
585 my $job_size = shift;
587 my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
588 my $jobID = $job->id();
591 if (my $pid = fork) {
593 # return job ID as JSON
595 # prevent parent exiting from
596 # destroying the kid's database handle
597 # FIXME: according to DBI doc, this may not work for Oracle
598 $dbh->{InactiveDestroy} = 1;
600 my $reply = CGI->new("");
601 print $reply->header(-type => 'text/html');
602 print '{"jobID":"' . $jobID . '"}';
604 } elsif (defined $pid) {
606 # close STDOUT to signal to Apache that
607 # we're now running in the background
611 # fork failed, so exit immediately
612 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
618 sub progress_callback {
622 my $progress = shift;
623 $job->progress($progress);