Merge remote branch 'kc/new/for-3.4/spelling' into kcmaster
[koha.git] / tools / batchMod.pl
blob5271d8142d50d8789ee4b504a3df750e74c070cc
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 Switch;
36 use MARC::File::XML;
38 my $input = new CGI;
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');
48 my $template_name;
49 my $template_flag;
50 if (!defined $op) {
51 $template_name = "tools/batchMod.tmpl";
52 $template_flag = { tools => '*' };
53 } else {
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,
61 query => $input,
62 type => "intranet",
63 authnotrequired => 0,
64 flagsrequired => $template_flag,
65 });
68 my $today_iso = C4::Dates->today('iso');
69 $template->param(today_iso => $today_iso);
70 $template->param(del => $del);
72 my $itemrecord;
73 my $nextop="";
74 my @errors; # store errors found while checking data BEFORE saving item.
75 my $items_display_hashref;
76 my $frameworkcode="";
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 # build indicator hash.
94 my @ind_tag = $input->param('ind_tag');
95 my @indicator = $input->param('indicator');
97 # Is there something to modify ?
98 # TODO : We shall use this var to warn the user in case no modification was done to the items
99 my $something_to_modify = scalar(grep {!/^$/} @values);
101 # Once the job is done
102 if ($completedJobID) {
103 # If we have a reasonable amount of items, we display them
104 if (scalar(@itemnumbers) <= 1000) {
105 $items_display_hashref=BuildItemsData(@itemnumbers);
106 } else {
107 # Else, we only display the barcode
108 my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
109 $template->param("simple_items_display" => \@simple_items_display);
112 # Setting the job as done
113 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
115 # Calling the template
116 add_saved_job_results_to_template($template, $completedJobID);
118 # While the job is getting done
119 } else {
121 # Job size is the number of items we have to process
122 my $job_size = scalar(@itemnumbers);
123 my $job = undef;
124 my $callback = sub {};
126 # If we asked for background processing
127 if ($runinbackground) {
128 $job = put_in_background($job_size);
129 $callback = progress_callback($job, $dbh);
132 # For each item
133 my $i = 1;
134 foreach my $itemnumber(@itemnumbers){
136 $job->progress($i) if $runinbackground;
137 my $itemdata=GetItem($itemnumber);
138 if ($input->param("del")){
139 my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
140 if ($return == 1) {
141 $deleted_items++;
142 } else {
143 $not_deleted_items++;
144 push @not_deleted, { biblionumber => $itemdata->{'biblionumber'}, itemnumber => $itemdata->{'itemnumber'}, barcode => $itemdata->{'barcode'}, title => $itemdata->{'title'}, $return => 1 };
146 } else {
147 if ($something_to_modify) {
148 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
149 my $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
150 my $localitem = TransformMarcToKoha( $dbh, $marcitem, "", 'items' );
151 my $localmarcitem=Item2Marc($itemdata);
152 UpdateMarcWith($marcitem,$localmarcitem);
153 eval{my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($localmarcitem,$itemdata->{biblionumber},$itemnumber)};
156 $i++;
161 #-------------------------------------------------------------------------------
162 # build screen with existing items. and "new" one
163 #-------------------------------------------------------------------------------
165 if ($op eq "show"){
166 my $filefh = $input->upload('uploadfile');
167 my $filecontent = $input->param('filecontent');
168 my @notfoundbarcodes;
170 my @contentlist;
171 if ($filefh){
172 while (my $content=<$filefh>){
173 chomp $content;
174 push @contentlist, $content if $content;
177 switch ($filecontent) {
178 case "barcode_file" {
179 foreach my $barcode (@contentlist) {
181 my $itemnumber = GetItemnumberFromBarcode($barcode);
182 if ($itemnumber) {
183 push @itemnumbers,$itemnumber;
184 } else {
185 push @notfoundbarcodes, $barcode;
191 case "itemid_file" {
192 @itemnumbers = @contentlist;
195 } else {
196 if ( my $list=$input->param('barcodelist')){
197 push my @barcodelist, split(/\s\n/, $list);
199 foreach my $barcode (@barcodelist) {
201 my $itemnumber = GetItemnumberFromBarcode($barcode);
202 if ($itemnumber) {
203 push @itemnumbers,$itemnumber;
204 } else {
205 push @notfoundbarcodes, $barcode;
211 # Only display the items if there are no more than 1000
212 if (scalar(@itemnumbers) <= 1000) {
213 $items_display_hashref=BuildItemsData(@itemnumbers);
214 } else {
215 $template->param("too_many_items" => scalar(@itemnumbers));
216 # Even if we do not display the items, we need the itemnumbers
217 my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
218 $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
220 # now, build the item form for entering a new item
221 my @loop_data =();
222 my $i=0;
223 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
225 my $branches = GetBranchesLoop(); # build once ahead of time, instead of multiple times later.
227 # Adding a default choice, in case the user does not want to modify the branch
228 my $nochange_branch = { branchname => '', value => '', selected => 1 };
229 unshift (@$branches, $nochange_branch);
231 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
234 foreach my $tag (sort keys %{$tagslib}) {
235 # loop through each subfield
236 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
237 next if subfield_is_koha_internal_p($subfield);
238 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
239 # barcode and stocknumber are not meant to be batch-modified
240 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
241 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
242 my %subfield_data;
244 my $index_subfield = int(rand(1000000));
245 if ($subfield eq '@'){
246 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
247 } else {
248 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
250 $subfield_data{tag} = $tag;
251 $subfield_data{subfield} = $subfield;
252 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
253 # $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
254 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
255 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
256 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
257 my ($x,$value);
258 $value =~ s/"/&quot;/g;
259 unless ($value) {
260 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
261 # get today date & replace YYYY, MM, DD if provided in the default value
262 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
263 $value =~ s/YYYY/$year/g;
264 $value =~ s/MM/$month/g;
265 $value =~ s/DD/$day/g;
267 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
268 # testing branch value if IndependantBranches.
270 my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
271 my $attributes = qq($attributes_no_value value="$value" );
273 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
274 my @authorised_values;
275 my %authorised_lib;
276 # builds list, depending on authorised value...
278 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
279 foreach my $thisbranch (@$branches) {
280 push @authorised_values, $thisbranch->{value};
281 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
283 $value = "";
285 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
286 push @authorised_values, "";
287 my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
288 $sth->execute;
289 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
290 push @authorised_values, $itemtype;
291 $authorised_lib{$itemtype} = $description;
293 $value = "";
295 #---- class_sources
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 = '';
312 #---- "true" authorised value
314 else {
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,
325 -default => $value,
326 -labels => \%authorised_lib,
327 -override => 1,
328 -size => 1,
329 -multiple => 0,
330 -tabindex => 1,
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} ) {
344 # opening plugin
345 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
346 if (do $plugin) {
347 my $temp;
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>
354 $javascript];
355 } else {
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";
374 } else {
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);
380 $i++
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);
391 $nextop="action"
392 } # -- End action="show"
394 $template->param(%$items_display_hashref) if $items_display_hashref;
395 $template->param(
396 op => $nextop,
397 $op => 1,
400 if ($op eq "action") {
402 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
404 $template->param(
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;
415 exit;
418 # ---------------- Functions
420 sub BuildItemsData{
421 my @itemnumbers=@_;
422 # now, build existiing item list
423 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
424 my @big_array;
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);
431 my %this_row;
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")) {
435 #verifying rights
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)
452 || $subfvalue;
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)});
464 if (%this_row) {
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
472 my @item_value_loop;
473 my @witnesscodessorted=sort keys %witness;
474 for my $row ( @big_array ) {
475 my %row_data;
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
493 # And $tag>10
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;
508 sub find_value {
509 my ($tagfield,$insubfield,$record) = @_;
510 my $result;
511 my $indicator;
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;
530 my $results = 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();
548 # fork off
549 if (my $pid = fork) {
550 # parent
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' }";
561 exit 0;
562 } elsif (defined $pid) {
563 # child
564 # close STDOUT to signal to Apache that
565 # we're now running in the background
566 close STDOUT;
567 close STDERR;
568 } else {
569 # fork failed, so exit immediately
570 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
571 exit 0;
573 return $job;
576 sub progress_callback {
577 my $job = shift;
578 my $dbh = shift;
579 return sub {
580 my $progress = shift;
581 $job->progress($progress);