bug 4451 followup - don't need /g for this replace
[koha.git] / tools / batchMod.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
16 #
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.
20
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;
36
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');
45
46
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' };
55 }
56
57
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                  });
65
66
67 my $today_iso = C4::Dates->today('iso');
68 $template->param(today_iso => $today_iso);
69 $template->param(del       => $del);
70
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);
77
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
81
82 my %cookies = parse CGI::Cookie($cookie);
83 my $sessionID = $cookies{'CGISESSID'}->value;
84
85
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');
95
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);
99
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);
109         }
110
111         # Setting the job as done
112         my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
113
114         # Calling the template
115         add_saved_job_results_to_template($template, $completedJobID);
116
117     # While the job is getting done
118     } else {
119
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 {};
124
125         # If we asked for background processing
126         if ($runinbackground) {
127             $job = put_in_background($job_size);
128             $callback = progress_callback($job, $dbh);
129         }
130
131         # For each item
132         my $i = 1; 
133         foreach my $itemnumber(@itemnumbers){
134
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 };
144                         }
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)};
153                     }
154                 }
155                 $i++;
156         }
157     }
158 }
159 #
160 #-------------------------------------------------------------------------------
161 # build screen with existing items. and "new" one
162 #-------------------------------------------------------------------------------
163
164 if ($op eq "show"){
165     my $filefh = $input->upload('uploadfile');
166     my $filecontent = $input->param('filecontent');
167     my @notfoundbarcodes;
168
169     my @contentlist;
170     if ($filefh){
171         while (my $content=<$filefh>){
172             $content =~ s/[\r\n]*$//;
173             push @contentlist, $content if $content;
174         }
175
176         if ($filecontent eq 'barcode_file') {
177             foreach my $barcode (@contentlist) {
178
179                 my $itemnumber = GetItemnumberFromBarcode($barcode);
180                 if ($itemnumber) {
181                     push @itemnumbers,$itemnumber;
182                 } else {
183                     push @notfoundbarcodes, $barcode;
184                 }
185             }
186         }
187         elsif ( $filecontent eq 'itemid_file') {
188             @itemnumbers = @contentlist;
189         }
190     } else {
191         if ( my $list=$input->param('barcodelist')){
192             push my @barcodelist, split(/\s\n/, $list);
193
194             foreach my $barcode (@barcodelist) {
195
196                 my $itemnumber = GetItemnumberFromBarcode($barcode);
197                 if ($itemnumber) {
198                     push @itemnumbers,$itemnumber;
199                 } else {
200                     push @notfoundbarcodes, $barcode;
201                 }
202             }
203
204         }
205     }
206     # Only display the items if there are no more than 1000
207     if (scalar(@itemnumbers) <= 1000) {
208         $items_display_hashref=BuildItemsData(@itemnumbers);
209     } else {
210         $template->param("too_many_items" => scalar(@itemnumbers));
211         # Even if we do not display the items, we need the itemnumbers
212         my @itemnumbers_hashref = map {{itemnumber => $_}} @itemnumbers;
213         $template->param("itemnumbers_hashref" => \@itemnumbers_hashref);
214     }
215 # now, build the item form for entering a new item
216 my @loop_data =();
217 my $i=0;
218 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
219
220 my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
221
222 # Adding a default choice, in case the user does not want to modify the branch
223 my $nochange_branch = { branchname => '', value => '', selected => 1 };
224 unshift (@$branches, $nochange_branch);
225
226 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
227
228
229 foreach my $tag (sort keys %{$tagslib}) {
230     # loop through each subfield
231     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
232         next if subfield_is_koha_internal_p($subfield);
233         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
234         # barcode and stocknumber are not meant to be batch-modified
235         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
236         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
237         my %subfield_data;
238  
239         my $index_subfield = int(rand(1000000)); 
240         if ($subfield eq '@'){
241             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
242         } else {
243             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
244         }
245         $subfield_data{tag}        = $tag;
246         $subfield_data{subfield}   = $subfield;
247         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
248     #   $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
249         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
250         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
251         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
252         my ($x,$value);
253         $value =~ s/"/&quot;/g;
254         unless ($value) {
255             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
256             # get today date & replace YYYY, MM, DD if provided in the default value
257             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
258             $value =~ s/YYYY/$year/g;
259             $value =~ s/MM/$month/g;
260             $value =~ s/DD/$day/g;
261         }
262         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
263         # testing branch value if IndependantBranches.
264
265         my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
266         my $attributes          = qq($attributes_no_value value="$value" );
267
268         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
269         my @authorised_values;
270         my %authorised_lib;
271         # builds list, depending on authorised value...
272   
273         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
274             foreach my $thisbranch (@$branches) {
275                 push @authorised_values, $thisbranch->{value};
276                 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
277             }
278         $value = "";
279         }
280         elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
281             push @authorised_values, "";
282             my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
283             $sth->execute;
284             while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
285                 push @authorised_values, $itemtype;
286                 $authorised_lib{$itemtype} = $description;
287             }
288         $value = "";
289
290           #---- class_sources
291       }
292       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
293           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
294             
295           my $class_sources = GetClassSources();
296           my $default_source = C4::Context->preference("DefaultClassificationSource");
297           
298           foreach my $class_source (sort keys %$class_sources) {
299               next unless $class_sources->{$class_source}->{'used'} or
300                           ($value and $class_source eq $value)      or
301                           ($class_source eq $default_source);
302               push @authorised_values, $class_source;
303               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
304           }
305                   $value = '';
306
307           #---- "true" authorised value
308       }
309       else {
310           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
311           $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
312           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
313               push @authorised_values, $value;
314               $authorised_lib{$value} = $lib;
315           }
316       }
317       $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
318           -name     => "field_value",
319           -values   => \@authorised_values,
320           -default  => $value,
321           -labels   => \%authorised_lib,
322           -override => 1,
323           -size     => 1,
324           -multiple => 0,
325           -tabindex => 1,
326           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
327           -class    => "input_marceditor",
328       );
329     # it's a thesaurus / authority field
330     }
331     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
332         $subfield_data{marc_value} = "<input type=\"text\" $attributes />
333             <a href=\"#\" class=\"buttonDot\"
334                 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>
335     ";
336     # it's a plugin field
337     }
338     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
339         # opening plugin
340         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
341         if (do $plugin) {
342                         my $temp;
343             my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
344             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
345             $subfield_data{marc_value} = qq[<input $attributes
346                 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
347                  onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
348                 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
349                 $javascript];
350         } else {
351             warn "Plugin Failed: $plugin";
352             $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
353         }
354     }
355     elsif ( $tag eq '' ) {       # it's an hidden field
356         $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
357     }
358     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
359         $subfield_data{marc_value} = qq(<input type="text" $attributes />);
360     }
361     elsif ( length($value) > 100
362             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
363                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
364             or (C4::Context->preference("marcflavour") eq "MARC21"  and
365                   500 <= $tag && $tag < 600                     )
366           ) {
367         # oversize field (textarea)
368         $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
369     } else {
370         # it's a standard field
371          $subfield_data{marc_value} = "<input $attributes />";
372     }
373 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
374     push (@loop_data, \%subfield_data);
375     $i++
376   }
377 } # -- End foreach tag
378
379
380     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
381     $template->param(item => \@loop_data);
382     if (@notfoundbarcodes) { 
383         my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
384         $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
385     }
386     $nextop="action"
387 } # -- End action="show"
388
389 $template->param(%$items_display_hashref) if $items_display_hashref;
390 $template->param(
391     op      => $nextop,
392     $op => 1,
393 );
394
395 if ($op eq "action") {
396
397     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
398
399     $template->param(
400         not_deleted_items => $not_deleted_items,
401         deleted_items => $deleted_items,
402         not_deleted_loop => \@not_deleted 
403     );
404 }
405
406 foreach my $error (@errors) {
407     $template->param($error => 1);
408 }
409 output_html_with_http_headers $input, $cookie, $template->output;
410 exit;
411
412
413 # ---------------- Functions
414
415 sub BuildItemsData{
416         my @itemnumbers=@_;
417                 # now, build existiing item list
418                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
419                 my @big_array;
420                 #---- finds where items.itemnumber is stored
421                 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
422                 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
423                 foreach my $itemnumber (@itemnumbers){
424                         my $itemdata=GetItem($itemnumber);
425                         my $itemmarc=Item2Marc($itemdata);
426                         my %this_row;
427                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
428                                 # loop through each subfield
429                                 if (my $itembranchcode=$field->subfield($branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
430                                                 #verifying rights
431                                                 my $userenv = C4::Context->userenv();
432                                                 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
433                                                                 $this_row{'nomod'}=1;
434                                                 }
435                                 }
436                                 my $tag=$field->tag();
437                                 foreach my $subfield ($field->subfields) {
438                                         my ($subfcode,$subfvalue)=@$subfield;
439                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
440                                                         && $tag        ne $itemtagfield 
441                                                         && $subfcode   ne $itemtagsubfield);
442
443                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
444                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
445                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
446                                                                         $subfcode, $subfvalue, '', $tagslib) 
447                                                                         || $subfvalue;
448                                         }
449
450                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
451                                 }
452                         }
453
454             # grab title, author, and ISBN to identify bib that the item
455             # belongs to in the display
456                         my $biblio=GetBiblioData($$itemdata{biblionumber});
457             $this_row{bibinfo} = join("\n", @$biblio{qw(title author ISBN)});
458
459                         if (%this_row) {
460                                 push(@big_array, \%this_row);
461                         }
462                 }
463                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
464
465                 # now, construct template !
466                 # First, the existing items for display
467                 my @item_value_loop;
468                 my @witnesscodessorted=sort keys %witness;
469                 for my $row ( @big_array ) {
470                         my %row_data;
471                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
472                         $row_data{item_value} = [ @item_fields ];
473                         $row_data{itemnumber} = $row->{itemnumber};
474                         #reporting this_row values
475                         $row_data{'nomod'} = $row->{'nomod'};
476             $row_data{bibinfo} = $row->{bibinfo};
477                         push(@item_value_loop,\%row_data);
478                 }
479                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
480
481         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
482 }
483
484 #BE WARN : it is not the general case 
485 # This function can be OK in the item marc record special case
486 # Where subfield is not repeated
487 # And where we are sure that field should correspond
488 # And $tag>10
489 sub UpdateMarcWith {
490   my ($marcfrom,$marcto)=@_;
491   #warn "FROM :",$marcfrom->as_formatted;
492         my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
493         my $fieldfrom=$marcfrom->field($itemtag);
494         my @fields_to=$marcto->field($itemtag);
495     foreach my $subfield ($fieldfrom->subfields()){
496                 foreach my $field_to_update (@fields_to){
497                                 $field_to_update->update($$subfield[0]=>$$subfield[1]) if ($$subfield[1]);
498                 }
499     }
500   #warn "TO edited:",$marcto->as_formatted;
501 }
502
503 sub find_value {
504     my ($tagfield,$insubfield,$record) = @_;
505     my $result;
506     my $indicator;
507     foreach my $field ($record->field($tagfield)) {
508         my @subfields = $field->subfields();
509         foreach my $subfield (@subfields) {
510             if (@$subfield[0] eq $insubfield) {
511                 $result .= @$subfield[1];
512                 $indicator = $field->indicator(1).$field->indicator(2);
513             }
514         }
515     }
516     return($indicator,$result);
517 }
518
519 # ----------------------------
520 # Background functions
521
522
523 sub add_results_to_template {
524     my $template = shift;
525     my $results = shift;
526     $template->param(map { $_ => $results->{$_} } keys %{ $results });
527 }
528
529 sub add_saved_job_results_to_template {
530     my $template = shift;
531     my $completedJobID = shift;
532     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
533     my $results = $job->results();
534     add_results_to_template($template, $results);
535 }
536
537 sub put_in_background {
538     my $job_size = shift;
539
540     my $job = C4::BackgroundJob->new($sessionID, "test", $ENV{'SCRIPT_NAME'}, $job_size);
541     my $jobID = $job->id();
542
543     # fork off
544     if (my $pid = fork) {
545         # parent
546         # return job ID as JSON
547
548         # prevent parent exiting from
549         # destroying the kid's database handle
550         # FIXME: according to DBI doc, this may not work for Oracle
551         $dbh->{InactiveDestroy}  = 1;
552
553         my $reply = CGI->new("");
554         print $reply->header(-type => 'text/html');
555         print "{ jobID: '$jobID' }";
556         exit 0;
557     } elsif (defined $pid) {
558         # child
559         # close STDOUT to signal to Apache that
560         # we're now running in the background
561         close STDOUT;
562         close STDERR;
563     } else {
564         # fork failed, so exit immediately
565         warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
566         exit 0;
567     }
568     return $job;
569 }
570
571 sub progress_callback {
572     my $job = shift;
573     my $dbh = shift;
574     return sub {
575         my $progress = shift;
576         $job->progress($progress);
577     }
578 }
579
580