Fix for Bug 5650, item type page key wrong
[koha.git] / tools / batchMod.pl
blob921c4d66b03839c97bae22e578e83ea70ff56efe
1 #!/usr/bin/perl
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
11 # version.
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.
21 use CGI;
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use C4::Auth;
25 use C4::Output;
26 use C4::Biblio;
27 use C4::Items;
28 use C4::Context;
29 use C4::Koha; # XXX subfield_is_koha_internal_p
30 use C4::Branch; # XXX subfield_is_koha_internal_p
31 use C4::BackgroundJob;
32 use C4::ClassSource;
33 use C4::Dates;
34 use C4::Debug;
35 use MARC::File::XML;
37 my $input = new CGI;
38 my $dbh = C4::Context->dbh;
39 my $error = $input->param('error');
40 my @itemnumbers = $input->param('itemnumber');
41 my $op = $input->param('op');
42 my $del = $input->param('del');
43 my $completedJobID = $input->param('completedJobID');
44 my $runinbackground = $input->param('runinbackground');
47 my $template_name;
48 my $template_flag;
49 if (!defined $op) {
50 $template_name = "tools/batchMod.tmpl";
51 $template_flag = { tools => '*' };
52 } else {
53 $template_name = ($del) ? "tools/batchMod-del.tmpl" : "tools/batchMod-edit.tmpl";
54 $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' };
58 my ($template, $loggedinuser, $cookie)
59 = get_template_and_user({template_name => $template_name,
60 query => $input,
61 type => "intranet",
62 authnotrequired => 0,
63 flagsrequired => $template_flag,
64 });
67 my $today_iso = C4::Dates->today('iso');
68 $template->param(today_iso => $today_iso);
69 $template->param(del => $del);
71 my $itemrecord;
72 my $nextop="";
73 my @errors; # store errors found while checking data BEFORE saving item.
74 my $items_display_hashref;
75 my $frameworkcode="";
76 my $tagslib = &GetMarcStructure(1,$frameworkcode);
78 my $deleted_items = 0; # Numbers of deleted items
79 my $not_deleted_items = 0; # Numbers of items that could not be deleted
80 my @not_deleted; # List of the itemnumbers that could not be deleted
82 my %cookies = parse CGI::Cookie($cookie);
83 my $sessionID = $cookies{'CGISESSID'}->value;
86 #--- ----------------------------------------------------------------------------
87 if ($op eq "action") {
88 #-------------------------------------------------------------------------------
89 my @tags = $input->param('tag');
90 my @subfields = $input->param('subfield');
91 my @values = $input->param('field_value');
92 # build indicator hash.
93 my @ind_tag = $input->param('ind_tag');
94 my @indicator = $input->param('indicator');
96 # Is there something to modify ?
97 # TODO : We shall use this var to warn the user in case no modification was done to the items
98 my $something_to_modify = scalar(grep {!/^$/} @values);
100 # Once the job is done
101 if ($completedJobID) {
102 # If we have a reasonable amount of items, we display them
103 if (scalar(@itemnumbers) <= 1000) {
104 $items_display_hashref=BuildItemsData(@itemnumbers);
105 } else {
106 # Else, we only display the barcode
107 my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
108 $template->param("simple_items_display" => \@simple_items_display);
111 # Setting the job as done
112 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
114 # Calling the template
115 add_saved_job_results_to_template($template, $completedJobID);
117 # While the job is getting done
118 } else {
120 # Job size is the number of items we have to process
121 my $job_size = scalar(@itemnumbers);
122 my $job = undef;
123 my $callback = sub {};
125 # If we asked for background processing
126 if ($runinbackground) {
127 $job = put_in_background($job_size);
128 $callback = progress_callback($job, $dbh);
131 # For each item
132 my $i = 1;
133 foreach my $itemnumber(@itemnumbers){
135 $job->progress($i) if $runinbackground;
136 my $itemdata=GetItem($itemnumber);
137 if ($input->param("del")){
138 my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
139 if ($return == 1) {
140 $deleted_items++;
141 } else {
142 $not_deleted_items++;
143 push @not_deleted, { biblionumber => $itemdata->{'biblionumber'}, itemnumber => $itemdata->{'itemnumber'}, barcode => $itemdata->{'barcode'}, title => $itemdata->{'title'}, $return => 1 };
145 } else {
146 if ($something_to_modify) {
147 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
148 my $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
149 my $localitem = TransformMarcToKoha( $dbh, $marcitem, "", 'items' );
150 my $localmarcitem=Item2Marc($itemdata);
151 UpdateMarcWith($marcitem,$localmarcitem);
152 eval{my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($localmarcitem,$itemdata->{biblionumber},$itemnumber)};
155 $i++;
160 #-------------------------------------------------------------------------------
161 # build screen with existing items. and "new" one
162 #-------------------------------------------------------------------------------
164 if ($op eq "show"){
165 my $filefh = $input->upload('uploadfile');
166 my $filecontent = $input->param('filecontent');
167 my @notfoundbarcodes;
169 my @contentlist;
170 if ($filefh){
171 while (my $content=<$filefh>){
172 $content =~ s/[\r\n]*$//;
173 push @contentlist, $content if $content;
176 if ($filecontent eq 'barcode_file') {
177 foreach my $barcode (@contentlist) {
179 my $itemnumber = GetItemnumberFromBarcode($barcode);
180 if ($itemnumber) {
181 push @itemnumbers,$itemnumber;
182 } else {
183 push @notfoundbarcodes, $barcode;
187 elsif ( $filecontent eq 'itemid_file') {
188 @itemnumbers = @contentlist;
190 } else {
191 if ( my $list=$input->param('barcodelist')){
192 push my @barcodelist, split(/\s\n/, $list);
194 foreach my $barcode (@barcodelist) {
196 my $itemnumber = GetItemnumberFromBarcode($barcode);
197 if ($itemnumber) {
198 push @itemnumbers,$itemnumber;
199 } else {
200 push @notfoundbarcodes, $barcode;
207 # Flag to tell the template there are valid results, hidden or not
208 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
209 # Only display the items if there are no more than 1000
210 if (scalar(@itemnumbers) <= 1000) {
211 $items_display_hashref=BuildItemsData(@itemnumbers);
212 } else {
213 $template->param("too_many_items" => scalar(@itemnumbers));
214 # Even if we do not display the items, we need the itemnumbers
215 my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
216 $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
218 # now, build the item form for entering a new item
219 my @loop_data =();
220 my $i=0;
221 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
223 my $branches = GetBranchesLoop(); # build once ahead of time, instead of multiple times later.
225 # Adding a default choice, in case the user does not want to modify the branch
226 my $nochange_branch = { branchname => '', value => '', selected => 1 };
227 unshift (@$branches, $nochange_branch);
229 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
232 foreach my $tag (sort keys %{$tagslib}) {
233 # loop through each subfield
234 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
235 next if subfield_is_koha_internal_p($subfield);
236 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
237 # barcode and stocknumber are not meant to be batch-modified
238 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
239 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
240 my %subfield_data;
242 my $index_subfield = int(rand(1000000));
243 if ($subfield eq '@'){
244 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
245 } else {
246 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
248 $subfield_data{tag} = $tag;
249 $subfield_data{subfield} = $subfield;
250 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
251 # $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
252 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
253 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
254 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
255 my ($x,$value);
256 $value =~ s/"/&quot;/g;
257 unless ($value) {
258 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
259 # get today date & replace YYYY, MM, DD if provided in the default value
260 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
261 $value =~ s/YYYY/$year/g;
262 $value =~ s/MM/$month/g;
263 $value =~ s/DD/$day/g;
265 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
266 # testing branch value if IndependantBranches.
268 my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
269 my $attributes = qq($attributes_no_value value="$value" );
271 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
272 my @authorised_values;
273 my %authorised_lib;
274 # builds list, depending on authorised value...
276 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
277 foreach my $thisbranch (@$branches) {
278 push @authorised_values, $thisbranch->{value};
279 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
281 $value = "";
283 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
284 push @authorised_values, "";
285 my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
286 $sth->execute;
287 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
288 push @authorised_values, $itemtype;
289 $authorised_lib{$itemtype} = $description;
291 $value = "";
293 #---- class_sources
295 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
296 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
298 my $class_sources = GetClassSources();
299 my $default_source = C4::Context->preference("DefaultClassificationSource");
301 foreach my $class_source (sort keys %$class_sources) {
302 next unless $class_sources->{$class_source}->{'used'} or
303 ($value and $class_source eq $value) or
304 ($class_source eq $default_source);
305 push @authorised_values, $class_source;
306 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
308 $value = '';
310 #---- "true" authorised value
312 else {
313 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
314 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
315 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
316 push @authorised_values, $value;
317 $authorised_lib{$value} = $lib;
320 $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
321 -name => "field_value",
322 -values => \@authorised_values,
323 -default => $value,
324 -labels => \%authorised_lib,
325 -override => 1,
326 -size => 1,
327 -multiple => 0,
328 -tabindex => 1,
329 -id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
330 -class => "input_marceditor",
332 # it's a thesaurus / authority field
334 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
335 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
336 <a href=\"#\" class=\"buttonDot\"
337 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>
339 # it's a plugin field
341 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
342 # opening plugin
343 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
344 if (do $plugin) {
345 my $temp;
346 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
347 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
348 $subfield_data{marc_value} = qq[<input $attributes
349 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
350 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
351 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
352 $javascript];
353 } else {
354 warn "Plugin Failed: $plugin";
355 $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
358 elsif ( $tag eq '' ) { # it's an hidden field
359 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
361 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
362 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
364 elsif ( length($value) > 100
365 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
366 300 <= $tag && $tag < 400 && $subfield eq 'a' )
367 or (C4::Context->preference("marcflavour") eq "MARC21" and
368 500 <= $tag && $tag < 600 )
370 # oversize field (textarea)
371 $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
372 } else {
373 # it's a standard field
374 $subfield_data{marc_value} = "<input $attributes />";
376 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
377 push (@loop_data, \%subfield_data);
378 $i++
380 } # -- End foreach tag
383 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
384 $template->param(item => \@loop_data);
385 if (@notfoundbarcodes) {
386 my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
387 $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
389 $nextop="action"
390 } # -- End action="show"
392 $template->param(%$items_display_hashref) if $items_display_hashref;
393 $template->param(
394 op => $nextop,
395 $op => 1,
398 if ($op eq "action") {
400 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
402 $template->param(
403 not_deleted_items => $not_deleted_items,
404 deleted_items => $deleted_items,
405 not_deleted_loop => \@not_deleted
409 foreach my $error (@errors) {
410 $template->param($error => 1);
412 output_html_with_http_headers $input, $cookie, $template->output;
413 exit;
416 # ---------------- Functions
418 sub BuildItemsData{
419 my @itemnumbers=@_;
420 # now, build existiing item list
421 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
422 my @big_array;
423 #---- finds where items.itemnumber is stored
424 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
425 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
426 foreach my $itemnumber (@itemnumbers){
427 my $itemdata=GetItem($itemnumber);
428 my $itemmarc=Item2Marc($itemdata);
429 my %this_row;
430 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
431 # loop through each subfield
432 if (my $itembranchcode=$field->subfield($branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
433 #verifying rights
434 my $userenv = C4::Context->userenv();
435 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
436 $this_row{'nomod'}=1;
439 my $tag=$field->tag();
440 foreach my $subfield ($field->subfields) {
441 my ($subfcode,$subfvalue)=@$subfield;
442 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
443 && $tag ne $itemtagfield
444 && $subfcode ne $itemtagsubfield);
446 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
447 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
448 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
449 $subfcode, $subfvalue, '', $tagslib)
450 || $subfvalue;
453 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
457 # grab title, author, and ISBN to identify bib that the item
458 # belongs to in the display
459 my $biblio=GetBiblioData($$itemdata{biblionumber});
460 $this_row{title} = $biblio->{title};
461 $this_row{author} = $biblio->{author};
462 $this_row{isbn} = $biblio->{isbn};
463 $this_row{biblionumber} = $biblio->{biblionumber};
465 if (%this_row) {
466 push(@big_array, \%this_row);
469 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
471 # now, construct template !
472 # First, the existing items for display
473 my @item_value_loop;
474 my @witnesscodessorted=sort keys %witness;
475 for my $row ( @big_array ) {
476 my %row_data;
477 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
478 $row_data{item_value} = [ @item_fields ];
479 $row_data{itemnumber} = $row->{itemnumber};
480 #reporting this_row values
481 $row_data{'nomod'} = $row->{'nomod'};
482 $row_data{bibinfo} = $row->{bibinfo};
483 $row_data{author} = $row->{author};
484 $row_data{title} = $row->{title};
485 $row_data{isbn} = $row->{isbn};
486 $row_data{biblionumber} = $row->{biblionumber};
487 push(@item_value_loop,\%row_data);
489 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
491 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
494 #BE WARN : it is not the general case
495 # This function can be OK in the item marc record special case
496 # Where subfield is not repeated
497 # And where we are sure that field should correspond
498 # And $tag>10
499 sub UpdateMarcWith {
500 my ($marcfrom,$marcto)=@_;
501 #warn "FROM :",$marcfrom->as_formatted;
502 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
503 my $fieldfrom=$marcfrom->field($itemtag);
504 my @fields_to=$marcto->field($itemtag);
505 foreach my $subfield ($fieldfrom->subfields()){
506 foreach my $field_to_update (@fields_to){
507 $field_to_update->update($$subfield[0]=>$$subfield[1]) if ($$subfield[1] != '' or $$subfield[1] == '0');
510 #warn "TO edited:",$marcto->as_formatted;
513 sub find_value {
514 my ($tagfield,$insubfield,$record) = @_;
515 my $result;
516 my $indicator;
517 foreach my $field ($record->field($tagfield)) {
518 my @subfields = $field->subfields();
519 foreach my $subfield (@subfields) {
520 if (@$subfield[0] eq $insubfield) {
521 $result .= @$subfield[1];
522 $indicator = $field->indicator(1).$field->indicator(2);
526 return($indicator,$result);
529 # ----------------------------
530 # Background functions
533 sub add_results_to_template {
534 my $template = shift;
535 my $results = shift;
536 $template->param(map { $_ => $results->{$_} } keys %{ $results });
539 sub add_saved_job_results_to_template {
540 my $template = shift;
541 my $completedJobID = shift;
542 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
543 my $results = $job->results();
544 add_results_to_template($template, $results);
547 sub put_in_background {
548 my $job_size = shift;
550 my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
551 my $jobID = $job->id();
553 # fork off
554 if (my $pid = fork) {
555 # parent
556 # return job ID as JSON
558 # prevent parent exiting from
559 # destroying the kid's database handle
560 # FIXME: according to DBI doc, this may not work for Oracle
561 $dbh->{InactiveDestroy} = 1;
563 my $reply = CGI->new("");
564 print $reply->header(-type => 'text/html');
565 print "{ jobID: '$jobID' }";
566 exit 0;
567 } elsif (defined $pid) {
568 # child
569 # close STDOUT to signal to Apache that
570 # we're now running in the background
571 close STDOUT;
572 close STDERR;
573 } else {
574 # fork failed, so exit immediately
575 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
576 exit 0;
578 return $job;
581 sub progress_callback {
582 my $job = shift;
583 my $dbh = shift;
584 return sub {
585 my $progress = shift;
586 $job->progress($progress);