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
29 use C4::Koha; # XXX subfield_is_koha_internal_p
30 use C4::Branch; # XXX subfield_is_koha_internal_p
31 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;
85 my $dbh = C4::Context->dbh;
88 #--- ----------------------------------------------------------------------------
89 if ($op eq "action") {
90 #-------------------------------------------------------------------------------
91 my @tags = $input->param('tag');
92 my @subfields = $input->param('subfield');
93 my @values = $input->param('field_value');
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 $something_to_modify = scalar(grep {!/^$/} @values);
102 # Once the job is done
103 if ($completedJobID) {
104 # If we have a reasonable amount of items, we display them
105 if (scalar(@itemnumbers) <= 1000) {
106 $items_display_hashref=BuildItemsData(@itemnumbers);
108 # Else, we only display the barcode
109 my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
110 $template->param("simple_items_display" => \@simple_items_display);
113 # Setting the job as done
114 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
116 # Calling the template
117 add_saved_job_results_to_template($template, $completedJobID);
119 # While the job is getting done
122 # Job size is the number of items we have to process
123 my $job_size = scalar(@itemnumbers);
125 my $callback = sub {};
127 # If we asked for background processing
128 if ($runinbackground) {
129 $job = put_in_background($job_size);
130 $callback = progress_callback($job, $dbh);
135 foreach my $itemnumber(@itemnumbers){
137 $job->progress($i) if $runinbackground;
138 my $itemdata=GetItem($itemnumber);
139 if ($input->param("del")){
140 my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
144 $not_deleted_items++;
145 push @not_deleted, { biblionumber => $itemdata->{'biblionumber'}, itemnumber => $itemdata->{'itemnumber'}, barcode => $itemdata->{'barcode'}, title => $itemdata->{'title'}, $return => 1 };
148 if ($something_to_modify) {
149 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
150 my $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
151 my $localitem = TransformMarcToKoha( $dbh, $marcitem, "", 'items' );
152 my $localmarcitem=Item2Marc($itemdata);
153 UpdateMarcWith($marcitem,$localmarcitem);
154 eval{my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($localmarcitem,$itemdata->{biblionumber},$itemnumber)};
162 #-------------------------------------------------------------------------------
163 # build screen with existing items. and "new" one
164 #-------------------------------------------------------------------------------
167 my $filefh = $input->upload('uploadfile');
168 my $filecontent = $input->param('filecontent');
169 my @notfoundbarcodes;
173 while (my $content=<$filefh>){
175 push @contentlist, $content if $content;
178 switch ($filecontent) {
179 case "barcode_file" {
180 foreach my $barcode (@contentlist) {
182 my $itemnumber = GetItemnumberFromBarcode($barcode);
184 push @itemnumbers,$itemnumber;
186 push @notfoundbarcodes, $barcode;
193 @itemnumbers = @contentlist;
197 if ( my $list=$input->param('barcodelist')){
198 push my @barcodelist, split(/\s\n/, $list);
200 foreach my $barcode (@barcodelist) {
202 my $itemnumber = GetItemnumberFromBarcode($barcode);
204 push @itemnumbers,$itemnumber;
206 push @notfoundbarcodes, $barcode;
212 # Only display the items if there are no more than 1000
213 if (scalar(@itemnumbers) <= 1000) {
214 $items_display_hashref=BuildItemsData(@itemnumbers);
216 $template->param("too_many_items" => scalar(@itemnumbers));
217 # Even if we do not display the items, we need the itemnumbers
218 my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
219 $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
221 # now, build the item form for entering a new item
224 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
226 my $branches = GetBranchesLoop(); # build once ahead of time, instead of multiple times later.
228 # Adding a default choice, in case the user does not want to modify the branch
229 my $nochange_branch = { branchname => '', value => '', selected => 1 };
230 unshift (@$branches, $nochange_branch);
232 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
235 foreach my $tag (sort keys %{$tagslib}) {
236 # loop through each subfield
237 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
238 next if subfield_is_koha_internal_p($subfield);
239 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
240 # barcode and stocknumber are not meant to be batch-modified
241 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
242 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
245 my $index_subfield = int(rand(1000000));
246 if ($subfield eq '@'){
247 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
249 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
251 $subfield_data{tag} = $tag;
252 $subfield_data{subfield} = $subfield;
253 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
254 # $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
255 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
256 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
257 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
259 $value =~ s/"/"/g;
261 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
262 # get today date & replace YYYY, MM, DD if provided in the default value
263 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
264 $value =~ s/YYYY/$year/g;
265 $value =~ s/MM/$month/g;
266 $value =~ s/DD/$day/g;
268 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
269 # testing branch value if IndependantBranches.
271 my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
272 my $attributes = qq($attributes_no_value value="$value" );
274 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
275 my @authorised_values;
277 # builds list, depending on authorised value...
279 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
280 foreach my $thisbranch (@$branches) {
281 push @authorised_values, $thisbranch->{value};
282 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
286 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
287 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
288 my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
290 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
291 push @authorised_values, $itemtype;
292 $authorised_lib{$itemtype} = $description;
297 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
298 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
300 my $class_sources = GetClassSources();
301 my $default_source = C4::Context->preference("DefaultClassificationSource");
303 foreach my $class_source (sort keys %$class_sources) {
304 next unless $class_sources->{$class_source}->{'used'} or
305 ($value and $class_source eq $value) or
306 ($class_source eq $default_source);
307 push @authorised_values, $class_source;
308 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
310 $value = $default_source unless ($value);
312 #---- "true" authorised value
315 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
316 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
317 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
318 push @authorised_values, $value;
319 $authorised_lib{$value} = $lib;
322 $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
323 -name => "field_value",
324 -values => \@authorised_values,
326 -labels => \%authorised_lib,
331 -id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
332 -class => "input_marceditor",
334 # it's a thesaurus / authority field
336 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
337 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
338 <a href=\"#\" class=\"buttonDot\"
339 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>
341 # it's a plugin field
343 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
345 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
348 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
349 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
350 $subfield_data{marc_value} = qq[<input $attributes
351 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
352 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
353 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
356 warn "Plugin Failed: $plugin";
357 $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
360 elsif ( $tag eq '' ) { # it's an hidden field
361 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
363 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
364 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
366 elsif ( length($value) > 100
367 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
368 300 <= $tag && $tag < 400 && $subfield eq 'a' )
369 or (C4::Context->preference("marcflavour") eq "MARC21" and
370 500 <= $tag && $tag < 600 )
372 # oversize field (textarea)
373 $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
375 # it's a standard field
376 $subfield_data{marc_value} = "<input $attributes />";
378 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
379 push (@loop_data, \%subfield_data);
382 } # -- End foreach tag
385 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
386 $template->param(item => \@loop_data);
387 if (@notfoundbarcodes) {
388 my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
389 $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
392 } # -- End action="show"
394 $template->param(%$items_display_hashref) if $items_display_hashref;
400 if ($op eq "action") {
402 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
405 not_deleted_items => $not_deleted_items,
406 deleted_items => $deleted_items,
407 not_deleted_loop => \@not_deleted
411 foreach my $error (@errors) {
412 $template->param($error => 1);
414 output_html_with_http_headers $input, $cookie, $template->output;
418 # ---------------- Functions
422 # now, build existiing item list
423 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
425 #---- finds where items.itemnumber is stored
426 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
427 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
428 foreach my $itemnumber (@itemnumbers){
429 my $itemdata=GetItem($itemnumber);
430 my $itemmarc=Item2Marc($itemdata);
432 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
433 # loop through each subfield
434 if (my $itembranchcode=$field->subfield($branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
436 my $userenv = C4::Context->userenv();
437 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
438 $this_row{'nomod'}=1;
441 my $tag=$field->tag();
442 foreach my $subfield ($field->subfields) {
443 my ($subfcode,$subfvalue)=@$subfield;
444 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
445 && $tag ne $itemtagfield
446 && $subfcode ne $itemtagsubfield);
448 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
449 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
450 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
451 $subfcode, $subfvalue, '', $tagslib)
455 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
459 # grab title, author, and ISBN to identify bib that the item
460 # belongs to in the display
461 my $biblio=GetBiblioData($$itemdata{biblionumber});
462 $this_row{bibinfo} = join("\n", @$biblio{qw(title author ISBN)});
465 push(@big_array, \%this_row);
468 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
470 # now, construct template !
471 # First, the existing items for display
473 my @witnesscodessorted=sort keys %witness;
474 for my $row ( @big_array ) {
476 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
477 $row_data{item_value} = [ @item_fields ];
478 $row_data{itemnumber} = $row->{itemnumber};
479 #reporting this_row values
480 $row_data{'nomod'} = $row->{'nomod'};
481 $row_data{bibinfo} = $row->{bibinfo};
482 push(@item_value_loop,\%row_data);
484 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
486 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
489 #BE WARN : it is not the general case
490 # This function can be OK in the item marc record special case
491 # Where subfield is not repeated
492 # And where we are sure that field should correspond
494 sub UpdateMarcWith($$){
495 my ($marcfrom,$marcto)=@_;
496 #warn "FROM :",$marcfrom->as_formatted;
497 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
498 my $fieldfrom=$marcfrom->field($itemtag);
499 my @fields_to=$marcto->field($itemtag);
500 foreach my $subfield ($fieldfrom->subfields()){
501 foreach my $field_to_update (@fields_to){
502 $field_to_update->update($$subfield[0]=>$$subfield[1]) if ($$subfield[1]);
505 #warn "TO edited:",$marcto->as_formatted;
509 my ($tagfield,$insubfield,$record) = @_;
512 foreach my $field ($record->field($tagfield)) {
513 my @subfields = $field->subfields();
514 foreach my $subfield (@subfields) {
515 if (@$subfield[0] eq $insubfield) {
516 $result .= @$subfield[1];
517 $indicator = $field->indicator(1).$field->indicator(2);
521 return($indicator,$result);
524 # ----------------------------
525 # Background functions
528 sub add_results_to_template {
529 my $template = shift;
531 $template->param(map { $_ => $results->{$_} } keys %{ $results });
534 sub add_saved_job_results_to_template {
535 my $template = shift;
536 my $completedJobID = shift;
537 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
538 my $results = $job->results();
539 add_results_to_template($template, $results);
542 sub put_in_background {
543 my $job_size = shift;
545 my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
546 my $jobID = $job->id();
549 if (my $pid = fork) {
551 # return job ID as JSON
553 # prevent parent exiting from
554 # destroying the kid's database handle
555 # FIXME: according to DBI doc, this may not work for Oracle
556 $dbh->{InactiveDestroy} = 1;
558 my $reply = CGI->new("");
559 print $reply->header(-type => 'text/html');
560 print "{ jobID: '$jobID' }";
562 } elsif (defined $pid) {
564 # close STDOUT to signal to Apache that
565 # we're now running in the background
569 # fork failed, so exit immediately
570 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
576 sub progress_callback {
580 my $progress = shift;
581 $job->progress($progress);