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') 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;
350 $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
351 -name => "field_value",
352 -values => \@authorised_values,
354 -labels => \%authorised_lib,
359 -id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
360 -class => "input_marceditor",
362 # it's a thesaurus / authority field
364 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
365 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
366 <a href=\"#\" class=\"buttonDot\"
367 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>
369 # it's a plugin field
371 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
373 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
376 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
377 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
378 $subfield_data{marc_value} = qq[<input $attributes
379 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
380 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
381 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
384 warn "Plugin Failed: $plugin";
385 $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
388 elsif ( $tag eq '' ) { # it's an hidden field
389 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
391 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
392 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
394 elsif ( length($value) > 100
395 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
396 300 <= $tag && $tag < 400 && $subfield eq 'a' )
397 or (C4::Context->preference("marcflavour") eq "MARC21" and
398 500 <= $tag && $tag < 600 )
400 # oversize field (textarea)
401 $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
403 # it's a standard field
404 $subfield_data{marc_value} = "<input $attributes />";
406 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
407 push (@loop_data, \%subfield_data);
410 } # -- End foreach tag
413 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
414 $template->param(item => \@loop_data);
415 if (@notfoundbarcodes) {
416 my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
417 $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
420 } # -- End action="show"
422 $template->param(%$items_display_hashref) if $items_display_hashref;
428 if ($op eq "action") {
430 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
433 not_deleted_items => $not_deleted_items,
434 deleted_items => $deleted_items,
435 not_deleted_loop => \@not_deleted
439 foreach my $error (@errors) {
440 $template->param($error => 1);
442 output_html_with_http_headers $input, $cookie, $template->output;
446 # ---------------- Functions
450 # now, build existiing item list
451 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
453 #---- finds where items.itemnumber is stored
454 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
455 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
456 foreach my $itemnumber (@itemnumbers){
457 my $itemdata=GetItem($itemnumber);
458 my $itemmarc=Item2Marc($itemdata);
460 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
461 # loop through each subfield
462 my $itembranchcode=$field->subfield($branchtagsubfield);
463 if ($itembranchcode && C4::Context->preference("IndependantBranches")) {
465 my $userenv = C4::Context->userenv();
466 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
467 $this_row{'nomod'}=1;
470 my $tag=$field->tag();
471 foreach my $subfield ($field->subfields) {
472 my ($subfcode,$subfvalue)=@$subfield;
473 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
474 && $tag ne $itemtagfield
475 && $subfcode ne $itemtagsubfield);
477 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
478 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
479 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
480 $subfcode, $subfvalue, '', $tagslib)
484 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
488 # grab title, author, and ISBN to identify bib that the item
489 # belongs to in the display
490 my $biblio=GetBiblioData($$itemdata{biblionumber});
491 $this_row{title} = $biblio->{title};
492 $this_row{author} = $biblio->{author};
493 $this_row{isbn} = $biblio->{isbn};
494 $this_row{biblionumber} = $biblio->{biblionumber};
497 push(@big_array, \%this_row);
500 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
502 # now, construct template !
503 # First, the existing items for display
505 my @witnesscodessorted=sort keys %witness;
506 for my $row ( @big_array ) {
508 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
509 $row_data{item_value} = [ @item_fields ];
510 $row_data{itemnumber} = $row->{itemnumber};
511 #reporting this_row values
512 $row_data{'nomod'} = $row->{'nomod'};
513 $row_data{bibinfo} = $row->{bibinfo};
514 $row_data{author} = $row->{author};
515 $row_data{title} = $row->{title};
516 $row_data{isbn} = $row->{isbn};
517 $row_data{biblionumber} = $row->{biblionumber};
518 push(@item_value_loop,\%row_data);
520 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
522 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
525 #BE WARN : it is not the general case
526 # This function can be OK in the item marc record special case
527 # Where subfield is not repeated
528 # And where we are sure that field should correspond
531 my ($marcfrom,$marcto)=@_;
532 #warn "FROM :",$marcfrom->as_formatted;
533 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
534 my $fieldfrom=$marcfrom->field($itemtag);
535 my @fields_to=$marcto->field($itemtag);
536 foreach my $subfield ($fieldfrom->subfields()){
537 foreach my $field_to_update (@fields_to){
539 $field_to_update->update($subfield->[0]=>$subfield->[1]);
542 $field_to_update->delete_subfield(code=> $subfield->[0]);
546 #warn "TO edited:",$marcto->as_formatted;
550 my ($tagfield,$insubfield,$record) = @_;
553 foreach my $field ($record->field($tagfield)) {
554 my @subfields = $field->subfields();
555 foreach my $subfield (@subfields) {
556 if (@$subfield[0] eq $insubfield) {
557 $result .= @$subfield[1];
558 $indicator = $field->indicator(1).$field->indicator(2);
562 return($indicator,$result);
565 # ----------------------------
566 # Background functions
569 sub add_results_to_template {
570 my $template = shift;
572 $template->param(map { $_ => $results->{$_} } keys %{ $results });
575 sub add_saved_job_results_to_template {
576 my $template = shift;
577 my $completedJobID = shift;
578 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
579 my $results = $job->results();
580 add_results_to_template($template, $results);
583 sub put_in_background {
584 my $job_size = shift;
586 my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
587 my $jobID = $job->id();
590 if (my $pid = fork) {
592 # return job ID as JSON
594 # prevent parent exiting from
595 # destroying the kid's database handle
596 # FIXME: according to DBI doc, this may not work for Oracle
597 $dbh->{InactiveDestroy} = 1;
599 my $reply = CGI->new("");
600 print $reply->header(-type => 'text/html');
601 print '{"jobID":"' . $jobID . '"}';
603 } elsif (defined $pid) {
605 # close STDOUT to signal to Apache that
606 # we're now running in the background
610 # fork failed, so exit immediately
611 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
617 sub progress_callback {
621 my $progress = shift;
622 $job->progress($progress);