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 $branch_limit = C4
::Context
->userenv ? C4
::Context
->userenv->{"branch"} : "";
271 my $query = qq{SELECT authorised_value
, lib FROM authorised_values
};
272 $query .= qq{ LEFT JOIN authorised_values_branches ON
( id
= av_id
) } if $branch_limit;
273 $query .= qq{ WHERE category
= ?
};
274 $query .= qq{ AND
( branchcode
= ? OR branchcode IS NULL
) } if $branch_limit;
275 $query .= qq{ GROUP BY lib ORDER BY lib
, lib_opac
};
276 my $authorised_values_sth = $dbh->prepare( $query );
278 my $branches = GetBranchesLoop
(); # build once ahead of time, instead of multiple times later.
280 # Adding a default choice, in case the user does not want to modify the branch
281 my $nochange_branch = { branchname
=> '', value
=> '', selected
=> 1 };
282 unshift (@
$branches, $nochange_branch);
284 my $pref_itemcallnumber = C4
::Context
->preference('itemcallnumber');
287 foreach my $tag (sort keys %{$tagslib}) {
288 # loop through each subfield
289 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
290 next if subfield_is_koha_internal_p
($subfield);
291 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
292 # barcode and stocknumber are not meant to be batch-modified
293 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
294 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
297 my $index_subfield = int(rand(1000000));
298 if ($subfield eq '@'){
299 $subfield_data{id
} = "tag_".$tag."_subfield_00_".$index_subfield;
301 $subfield_data{id
} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
303 $subfield_data{tag
} = $tag;
304 $subfield_data{subfield
} = $subfield;
305 $subfield_data{random
} = int(rand(1000000)); # why do we need 2 different randoms?
306 # $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
307 $subfield_data{marc_lib
} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib
}."\">".$tagslib->{$tag}->{$subfield}->{lib
}."</span>";
308 $subfield_data{mandatory
} = $tagslib->{$tag}->{$subfield}->{mandatory
};
309 $subfield_data{repeatable
} = $tagslib->{$tag}->{$subfield}->{repeatable
};
311 $value =~ s/"/"/g;
313 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue
};
314 # get today date & replace YYYY, MM, DD if provided in the default value
315 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
316 $value =~ s/YYYY/$year/g;
317 $value =~ s/MM/$month/g;
318 $value =~ s/DD/$day/g;
320 $subfield_data{visibility
} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden
} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden
} < -4));
321 # testing branch value if IndependantBranches.
323 my $attributes_no_value = qq(tabindex
="1" id
="$subfield_data{id}" name
="field_value" class="input_marceditor" size
="67" maxlength
="255" );
324 my $attributes = qq($attributes_no_value value
="$value" );
326 if ( $tagslib->{$tag}->{$subfield}->{authorised_value
} ) {
327 my @authorised_values;
329 # builds list, depending on authorised value...
331 if ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "branches" ) {
332 foreach my $thisbranch (@
$branches) {
333 push @authorised_values, $thisbranch->{value
};
334 $authorised_lib{$thisbranch->{value
}} = $thisbranch->{branchname
};
338 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "itemtypes" ) {
339 push @authorised_values, "";
340 my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
342 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
343 push @authorised_values, $itemtype;
344 $authorised_lib{$itemtype} = $description;
350 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "cn_source" ) {
351 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
353 my $class_sources = GetClassSources
();
354 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
356 foreach my $class_source (sort keys %$class_sources) {
357 next unless $class_sources->{$class_source}->{'used'} or
358 ($value and $class_source eq $value) or
359 ($class_source eq $default_source);
360 push @authorised_values, $class_source;
361 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
365 #---- "true" authorised value
368 push @authorised_values, ""; # unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
369 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value
}, $branch_limit ?
$branch_limit : () );
370 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
371 push @authorised_values, $value;
372 $authorised_lib{$value} = $lib;
376 $subfield_data{marc_value
} =CGI
::scrolling_list
( # FIXME: factor out scrolling_list
377 -name
=> "field_value",
378 -values => \
@authorised_values,
380 -labels
=> \
%authorised_lib,
385 -id
=> "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
386 -class => "input_marceditor",
388 # it's a thesaurus / authority field
390 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode
} ) {
391 $subfield_data{marc_value
} = "<input type=\"text\" $attributes />
392 <a href=\"#\" class=\"buttonDot\"
393 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>
395 # it's a plugin field
397 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder
} ) {
399 my $plugin = C4
::Context
->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
402 my $extended_param = plugin_parameters
( $dbh, $temp, $tagslib, $subfield_data{id
}, \
@loop_data );
403 my ( $function_name, $javascript ) = plugin_javascript
( $dbh, $temp, $tagslib, $subfield_data{id
}, \
@loop_data );
404 $subfield_data{marc_value
} = qq[<input type
="text" $attributes
405 onfocus
="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
406 onblur
=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
407 <a href
="#" class="buttonDot" onclick
="Clic$function_name('$subfield_data{id}'); return false;" title
="Tag Editor">...</a
>
410 warn "Plugin Failed: $plugin";
411 $subfield_data{marc_value
} = "<input type=\"text\" $attributes />"; # supply default input form
414 elsif ( $tag eq '' ) { # it's an hidden field
415 $subfield_data{marc_value
} = qq(<input type
="hidden" $attributes />);
417 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
418 $subfield_data{marc_value
} = qq(<input type
="text" $attributes />);
420 elsif ( length($value) > 100
421 or (C4
::Context
->preference("marcflavour") eq "UNIMARC" and
422 300 <= $tag && $tag < 400 && $subfield eq 'a' )
423 or (C4
::Context
->preference("marcflavour") eq "MARC21" and
424 500 <= $tag && $tag < 600 )
426 # oversize field (textarea)
427 $subfield_data{marc_value
} = "<textarea $attributes_no_value>$value</textarea>\n";
429 # it's a standard field
430 $subfield_data{marc_value
} = "<input type=\"text\" $attributes />";
432 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
433 push (@loop_data, \
%subfield_data);
436 } # -- End foreach tag
437 $authorised_values_sth->finish;
441 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
442 $template->param(item
=> \
@loop_data);
443 if (@notfoundbarcodes) {
444 my @notfoundbarcodesloop = map{{barcode
=>$_}}@notfoundbarcodes;
445 $template->param(notfoundbarcodes
=> \
@notfoundbarcodesloop);
448 } # -- End action="show"
450 $template->param(%$items_display_hashref) if $items_display_hashref;
454 $template->param( $op => 1 ) if $op;
456 if ($op eq "action") {
458 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
461 not_deleted_items
=> $not_deleted_items,
462 deleted_items
=> $deleted_items,
463 delete_records
=> $del_records,
464 deleted_records
=> $deleted_records,
465 not_deleted_loop
=> \
@not_deleted
469 foreach my $error (@errors) {
470 $template->param($error => 1) if $error;
472 $template->param(src
=> $src);
473 $template->param(biblionumber
=> $biblionumber);
474 output_html_with_http_headers
$input, $cookie, $template->output;
478 # ---------------- Functions
482 # now, build existiing item list
483 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
485 #---- finds where items.itemnumber is stored
486 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField
("items.itemnumber", "");
487 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField
("items.homebranch", "");
488 foreach my $itemnumber (@itemnumbers){
489 my $itemdata=GetItem
($itemnumber);
490 my $itemmarc=Item2Marc
($itemdata);
492 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
493 # loop through each subfield
494 my $itembranchcode=$field->subfield($branchtagsubfield);
495 if ($itembranchcode && C4
::Context
->preference("IndependantBranches")) {
497 my $userenv = C4
::Context
->userenv();
498 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
499 $this_row{'nomod'}=1;
502 my $tag=$field->tag();
503 foreach my $subfield ($field->subfields) {
504 my ($subfcode,$subfvalue)=@
$subfield;
505 next if ($tagslib->{$tag}->{$subfcode}->{tab
} ne 10
506 && $tag ne $itemtagfield
507 && $subfcode ne $itemtagsubfield);
509 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib
} if ($tagslib->{$tag}->{$subfcode}->{tab
} eq 10);
510 if ($tagslib->{$tag}->{$subfcode}->{tab
} eq 10) {
511 $this_row{$subfcode}=GetAuthorisedValueDesc
( $tag,
512 $subfcode, $subfvalue, '', $tagslib)
516 $this_row{itemnumber
} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
520 # grab title, author, and ISBN to identify bib that the item
521 # belongs to in the display
522 my $biblio=GetBiblioData
($$itemdata{biblionumber
});
523 $this_row{title
} = $biblio->{title
};
524 $this_row{author
} = $biblio->{author
};
525 $this_row{isbn
} = $biblio->{isbn
};
526 $this_row{biblionumber
} = $biblio->{biblionumber
};
529 push(@big_array, \
%this_row);
532 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
534 # now, construct template !
535 # First, the existing items for display
537 my @witnesscodessorted=sort keys %witness;
538 for my $row ( @big_array ) {
540 my @item_fields = map +{ field
=> $_ || '' }, @
$row{ @witnesscodessorted };
541 $row_data{item_value
} = [ @item_fields ];
542 $row_data{itemnumber
} = $row->{itemnumber
};
543 #reporting this_row values
544 $row_data{'nomod'} = $row->{'nomod'};
545 $row_data{bibinfo
} = $row->{bibinfo
};
546 $row_data{author
} = $row->{author
};
547 $row_data{title
} = $row->{title
};
548 $row_data{isbn
} = $row->{isbn
};
549 $row_data{biblionumber
} = $row->{biblionumber
};
550 push(@item_value_loop,\
%row_data);
552 my @header_loop=map { { header_value
=> $witness{$_}} } @witnesscodessorted;
554 return { item_loop
=> \
@item_value_loop, item_header_loop
=> \
@header_loop };
557 #BE WARN : it is not the general case
558 # This function can be OK in the item marc record special case
559 # Where subfield is not repeated
560 # And where we are sure that field should correspond
563 my ($marcfrom,$marcto)=@_;
564 #warn "FROM :",$marcfrom->as_formatted;
565 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField
("items.itemnumber", "");
566 my $fieldfrom=$marcfrom->field($itemtag);
567 my @fields_to=$marcto->field($itemtag);
568 foreach my $subfield ($fieldfrom->subfields()){
569 foreach my $field_to_update (@fields_to){
571 $field_to_update->update($subfield->[0]=>$subfield->[1]);
574 $field_to_update->delete_subfield(code
=> $subfield->[0]);
578 #warn "TO edited:",$marcto->as_formatted;
582 my ($tagfield,$insubfield,$record) = @_;
585 foreach my $field ($record->field($tagfield)) {
586 my @subfields = $field->subfields();
587 foreach my $subfield (@subfields) {
588 if (@
$subfield[0] eq $insubfield) {
589 $result .= @
$subfield[1];
590 $indicator = $field->indicator(1).$field->indicator(2);
594 return($indicator,$result);
597 # ----------------------------
598 # Background functions
601 sub add_results_to_template
{
602 my $template = shift;
604 $template->param(map { $_ => $results->{$_} } keys %{ $results });
607 sub add_saved_job_results_to_template
{
608 my $template = shift;
609 my $completedJobID = shift;
610 my $job = C4
::BackgroundJob
->fetch($sessionID, $completedJobID);
611 my $results = $job->results();
612 add_results_to_template
($template, $results);
615 sub put_in_background
{
616 my $job_size = shift;
618 my $job = C4
::BackgroundJob
->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
619 my $jobID = $job->id();
622 if (my $pid = fork) {
624 # return job ID as JSON
626 # prevent parent exiting from
627 # destroying the kid's database handle
628 # FIXME: according to DBI doc, this may not work for Oracle
629 $dbh->{InactiveDestroy
} = 1;
631 my $reply = CGI
->new("");
632 print $reply->header(-type
=> 'text/html');
633 print '{"jobID":"' . $jobID . '"}';
635 } elsif (defined $pid) {
637 # close STDOUT to signal to Apache that
638 # we're now running in the background
642 # fork failed, so exit immediately
643 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";