Bug 6992 - add missing tab chars to history.txt
[koha.git] / tools / batchMod.pl
blob04cfc879c6edf7338c95e5a3abb3a93bc543feea
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 my @disabled = $input->param('disable_input');
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 $values_to_modify = scalar(grep {!/^$/} @values);
100 my $values_to_blank = scalar(@disabled);
101 my $marcitem;
103 # Once the job is done
104 if ($completedJobID) {
105 # If we have a reasonable amount of items, we display them
106 if (scalar(@itemnumbers) <= 1000) {
107 $items_display_hashref=BuildItemsData(@itemnumbers);
108 } else {
109 # Else, we only display the barcode
110 my @simple_items_display = map {{ itemnumber => $_, barcode => (GetBarcodeFromItemnumber($_) or ""), biblionumber => (GetBiblionumberFromItemnumber($_) or "") }} @itemnumbers;
111 $template->param("simple_items_display" => \@simple_items_display);
114 # Setting the job as done
115 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
117 # Calling the template
118 add_saved_job_results_to_template($template, $completedJobID);
120 } else {
121 # While the job is getting done
123 # Job size is the number of items we have to process
124 my $job_size = scalar(@itemnumbers);
125 my $job = undef;
126 my $callback = sub {};
128 # If we asked for background processing
129 if ($runinbackground) {
130 $job = put_in_background($job_size);
131 $callback = progress_callback($job, $dbh);
134 #initializing values for updates
135 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
136 if ($values_to_modify){
137 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
138 utf8::encode($xml);
139 $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
141 if ($values_to_blank){
142 foreach my $disabledsubf (@disabled){
143 if ($marcitem && $marcitem->field($itemtagfield)){
144 $marcitem->field($itemtagfield)->update( $disabledsubf => "" );
146 else {
147 $marcitem = MARC::Record->new();
148 $marcitem->append_fields( MARC::Field->new( $itemtagfield, '', '', $disabledsubf => "" ) );
153 # For each item
154 my $i = 1;
155 foreach my $itemnumber(@itemnumbers){
157 $job->progress($i) if $runinbackground;
158 my $itemdata=GetItem($itemnumber);
159 if ($input->param("del")){
160 my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
161 if ($return == 1) {
162 $deleted_items++;
163 } else {
164 $not_deleted_items++;
165 push @not_deleted,
166 { biblionumber => $itemdata->{'biblionumber'},
167 itemnumber => $itemdata->{'itemnumber'},
168 barcode => $itemdata->{'barcode'},
169 title => $itemdata->{'title'},
170 $return => 1
173 } else {
174 if ($values_to_modify || $values_to_blank) {
175 my $localmarcitem = Item2Marc($itemdata);
176 UpdateMarcWith( $marcitem, $localmarcitem );
177 eval{ my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = ModItemFromMarc( $localmarcitem, $itemdata->{biblionumber}, $itemnumber ) };
180 $i++;
185 #-------------------------------------------------------------------------------
186 # build screen with existing items. and "new" one
187 #-------------------------------------------------------------------------------
189 if ($op eq "show"){
190 my $filefh = $input->upload('uploadfile');
191 my $filecontent = $input->param('filecontent');
192 my @notfoundbarcodes;
194 my @contentlist;
195 if ($filefh){
196 while (my $content=<$filefh>){
197 $content =~ s/[\r\n]*$//;
198 push @contentlist, $content if $content;
201 if ($filecontent eq 'barcode_file') {
202 foreach my $barcode (@contentlist) {
204 my $itemnumber = GetItemnumberFromBarcode($barcode);
205 if ($itemnumber) {
206 push @itemnumbers,$itemnumber;
207 } else {
208 push @notfoundbarcodes, $barcode;
212 elsif ( $filecontent eq 'itemid_file') {
213 @itemnumbers = @contentlist;
215 } else {
216 if ( my $list=$input->param('barcodelist')){
217 push my @barcodelist, split(/\s\n/, $list);
219 foreach my $barcode (@barcodelist) {
221 my $itemnumber = GetItemnumberFromBarcode($barcode);
222 if ($itemnumber) {
223 push @itemnumbers,$itemnumber;
224 } else {
225 push @notfoundbarcodes, $barcode;
232 # Flag to tell the template there are valid results, hidden or not
233 if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); }
234 # Only display the items if there are no more than 1000
235 if (scalar(@itemnumbers) <= 1000) {
236 $items_display_hashref=BuildItemsData(@itemnumbers);
237 } else {
238 $template->param("too_many_items" => scalar(@itemnumbers));
239 # Even if we do not display the items, we need the itemnumbers
240 my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
241 $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
243 # now, build the item form for entering a new item
244 my @loop_data =();
245 my $i=0;
246 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
248 my $branches = GetBranchesLoop(); # build once ahead of time, instead of multiple times later.
250 # Adding a default choice, in case the user does not want to modify the branch
251 my $nochange_branch = { branchname => '', value => '', selected => 1 };
252 unshift (@$branches, $nochange_branch);
254 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
257 foreach my $tag (sort keys %{$tagslib}) {
258 # loop through each subfield
259 foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
260 next if subfield_is_koha_internal_p($subfield);
261 next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
262 # barcode and stocknumber are not meant to be batch-modified
263 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
264 next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
265 my %subfield_data;
267 my $index_subfield = int(rand(1000000));
268 if ($subfield eq '@'){
269 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
270 } else {
271 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
273 $subfield_data{tag} = $tag;
274 $subfield_data{subfield} = $subfield;
275 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
276 # $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
277 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
278 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
279 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
280 my ($x,$value);
281 $value =~ s/"/&quot;/g;
282 unless ($value) {
283 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
284 # get today date & replace YYYY, MM, DD if provided in the default value
285 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
286 $value =~ s/YYYY/$year/g;
287 $value =~ s/MM/$month/g;
288 $value =~ s/DD/$day/g;
290 $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
291 # testing branch value if IndependantBranches.
293 my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
294 my $attributes = qq($attributes_no_value value="$value" );
296 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
297 my @authorised_values;
298 my %authorised_lib;
299 # builds list, depending on authorised value...
301 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
302 foreach my $thisbranch (@$branches) {
303 push @authorised_values, $thisbranch->{value};
304 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
306 $value = "";
308 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
309 push @authorised_values, "";
310 my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
311 $sth->execute;
312 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
313 push @authorised_values, $itemtype;
314 $authorised_lib{$itemtype} = $description;
316 $value = "";
318 #---- class_sources
320 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
321 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
323 my $class_sources = GetClassSources();
324 my $default_source = C4::Context->preference("DefaultClassificationSource");
326 foreach my $class_source (sort keys %$class_sources) {
327 next unless $class_sources->{$class_source}->{'used'} or
328 ($value and $class_source eq $value) or
329 ($class_source eq $default_source);
330 push @authorised_values, $class_source;
331 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
333 $value = '';
335 #---- "true" authorised value
337 else {
338 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
339 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
340 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
341 push @authorised_values, $value;
342 $authorised_lib{$value} = $lib;
345 $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
346 -name => "field_value",
347 -values => \@authorised_values,
348 -default => $value,
349 -labels => \%authorised_lib,
350 -override => 1,
351 -size => 1,
352 -multiple => 0,
353 -tabindex => 1,
354 -id => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
355 -class => "input_marceditor",
357 # it's a thesaurus / authority field
359 elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
360 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
361 <a href=\"#\" class=\"buttonDot\"
362 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>
364 # it's a plugin field
366 elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
367 # opening plugin
368 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
369 if (do $plugin) {
370 my $temp;
371 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
372 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
373 $subfield_data{marc_value} = qq[<input $attributes
374 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
375 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
376 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
377 $javascript];
378 } else {
379 warn "Plugin Failed: $plugin";
380 $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
383 elsif ( $tag eq '' ) { # it's an hidden field
384 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
386 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
387 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
389 elsif ( length($value) > 100
390 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
391 300 <= $tag && $tag < 400 && $subfield eq 'a' )
392 or (C4::Context->preference("marcflavour") eq "MARC21" and
393 500 <= $tag && $tag < 600 )
395 # oversize field (textarea)
396 $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
397 } else {
398 # it's a standard field
399 $subfield_data{marc_value} = "<input $attributes />";
401 # $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
402 push (@loop_data, \%subfield_data);
403 $i++
405 } # -- End foreach tag
408 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
409 $template->param(item => \@loop_data);
410 if (@notfoundbarcodes) {
411 my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
412 $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
414 $nextop="action"
415 } # -- End action="show"
417 $template->param(%$items_display_hashref) if $items_display_hashref;
418 $template->param(
419 op => $nextop,
420 $op => 1,
423 if ($op eq "action") {
425 #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
427 $template->param(
428 not_deleted_items => $not_deleted_items,
429 deleted_items => $deleted_items,
430 not_deleted_loop => \@not_deleted
434 foreach my $error (@errors) {
435 $template->param($error => 1);
437 output_html_with_http_headers $input, $cookie, $template->output;
438 exit;
441 # ---------------- Functions
443 sub BuildItemsData{
444 my @itemnumbers=@_;
445 # now, build existiing item list
446 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
447 my @big_array;
448 #---- finds where items.itemnumber is stored
449 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
450 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
451 foreach my $itemnumber (@itemnumbers){
452 my $itemdata=GetItem($itemnumber);
453 my $itemmarc=Item2Marc($itemdata);
454 my %this_row;
455 foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
456 # loop through each subfield
457 my $itembranchcode=$field->subfield($branchtagsubfield);
458 if ($itembranchcode && C4::Context->preference("IndependantBranches")) {
459 #verifying rights
460 my $userenv = C4::Context->userenv();
461 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
462 $this_row{'nomod'}=1;
465 my $tag=$field->tag();
466 foreach my $subfield ($field->subfields) {
467 my ($subfcode,$subfvalue)=@$subfield;
468 next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10
469 && $tag ne $itemtagfield
470 && $subfcode ne $itemtagsubfield);
472 $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10);
473 if ($tagslib->{$tag}->{$subfcode}->{tab} eq 10) {
474 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
475 $subfcode, $subfvalue, '', $tagslib)
476 || $subfvalue;
479 $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
483 # grab title, author, and ISBN to identify bib that the item
484 # belongs to in the display
485 my $biblio=GetBiblioData($$itemdata{biblionumber});
486 $this_row{title} = $biblio->{title};
487 $this_row{author} = $biblio->{author};
488 $this_row{isbn} = $biblio->{isbn};
489 $this_row{biblionumber} = $biblio->{biblionumber};
491 if (%this_row) {
492 push(@big_array, \%this_row);
495 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
497 # now, construct template !
498 # First, the existing items for display
499 my @item_value_loop;
500 my @witnesscodessorted=sort keys %witness;
501 for my $row ( @big_array ) {
502 my %row_data;
503 my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
504 $row_data{item_value} = [ @item_fields ];
505 $row_data{itemnumber} = $row->{itemnumber};
506 #reporting this_row values
507 $row_data{'nomod'} = $row->{'nomod'};
508 $row_data{bibinfo} = $row->{bibinfo};
509 $row_data{author} = $row->{author};
510 $row_data{title} = $row->{title};
511 $row_data{isbn} = $row->{isbn};
512 $row_data{biblionumber} = $row->{biblionumber};
513 push(@item_value_loop,\%row_data);
515 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
517 return { item_loop => \@item_value_loop, item_header_loop => \@header_loop };
520 #BE WARN : it is not the general case
521 # This function can be OK in the item marc record special case
522 # Where subfield is not repeated
523 # And where we are sure that field should correspond
524 # And $tag>10
525 sub UpdateMarcWith {
526 my ($marcfrom,$marcto)=@_;
527 #warn "FROM :",$marcfrom->as_formatted;
528 my ( $itemtag, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
529 my $fieldfrom=$marcfrom->field($itemtag);
530 my @fields_to=$marcto->field($itemtag);
531 foreach my $subfield ($fieldfrom->subfields()){
532 foreach my $field_to_update (@fields_to){
533 if ($subfield->[1]){
534 $field_to_update->update($subfield->[0]=>$subfield->[1]);
536 else {
537 $field_to_update->delete_subfield(code=> $subfield->[0]);
541 #warn "TO edited:",$marcto->as_formatted;
544 sub find_value {
545 my ($tagfield,$insubfield,$record) = @_;
546 my $result;
547 my $indicator;
548 foreach my $field ($record->field($tagfield)) {
549 my @subfields = $field->subfields();
550 foreach my $subfield (@subfields) {
551 if (@$subfield[0] eq $insubfield) {
552 $result .= @$subfield[1];
553 $indicator = $field->indicator(1).$field->indicator(2);
557 return($indicator,$result);
560 # ----------------------------
561 # Background functions
564 sub add_results_to_template {
565 my $template = shift;
566 my $results = shift;
567 $template->param(map { $_ => $results->{$_} } keys %{ $results });
570 sub add_saved_job_results_to_template {
571 my $template = shift;
572 my $completedJobID = shift;
573 my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
574 my $results = $job->results();
575 add_results_to_template($template, $results);
578 sub put_in_background {
579 my $job_size = shift;
581 my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
582 my $jobID = $job->id();
584 # fork off
585 if (my $pid = fork) {
586 # parent
587 # return job ID as JSON
589 # prevent parent exiting from
590 # destroying the kid's database handle
591 # FIXME: according to DBI doc, this may not work for Oracle
592 $dbh->{InactiveDestroy} = 1;
594 my $reply = CGI->new("");
595 print $reply->header(-type => 'text/html');
596 print '{"jobID":"' . $jobID . '"}';
597 exit 0;
598 } elsif (defined $pid) {
599 # child
600 # close STDOUT to signal to Apache that
601 # we're now running in the background
602 close STDOUT;
603 close STDERR;
604 } else {
605 # fork failed, so exit immediately
606 warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
607 exit 0;
609 return $job;
612 sub progress_callback {
613 my $job = shift;
614 my $dbh = shift;
615 return sub {
616 my $progress = shift;
617 $job->progress($progress);