Bug 2505 - enable warnings for link_bibs_to_authorities
[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::ClassSource;
32 use C4::Dates;
33 use C4::Debug;
34 use YAML;
35 use Switch;
36 use MARC::File::XML;
37
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
45 my $template_name;
46 my $template_flag;
47 if (!defined $op) {
48     $template_name = "tools/batchMod.tmpl";
49     $template_flag = { tools => '*' };
50 } else {
51     $template_name = ($del) ? "tools/batchMod-del.tmpl" : "tools/batchMod-edit.tmpl";
52     $template_flag = ($del) ? { tools => 'batchdel' }   : { tools => 'batchmod' };
53 }
54
55
56 my ($template, $loggedinuser, $cookie)
57     = get_template_and_user({template_name => $template_name,
58                  query => $input,
59                  type => "intranet",
60                  authnotrequired => 0,
61                  flagsrequired => $template_flag,
62                  });
63
64
65 my $today_iso = C4::Dates->today('iso');
66 $template->param(today_iso => $today_iso);
67 $template->param(del       => $del);
68
69 my $itemrecord;
70 my $nextop="";
71 my @errors; # store errors found while checking data BEFORE saving item.
72 my $items_display_hashref;
73 my $frameworkcode="";
74 my $tagslib = &GetMarcStructure(1,$frameworkcode);
75
76 my $deleted_items = 0;     # Numbers of deleted items
77 my $not_deleted_items = 0; # Numbers of items that could not be deleted
78 my @not_deleted;           # List of the itemnumbers that could not be deleted
79
80 #--- ----------------------------------------------------------------------------
81 if ($op eq "action") {
82 #-------------------------------------------------------------------------------
83     my @tags      = $input->param('tag');
84     my @subfields = $input->param('subfield');
85     my @values    = $input->param('field_value');
86     # build indicator hash.
87     my @ind_tag   = $input->param('ind_tag');
88     my @indicator = $input->param('indicator');
89
90     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
91     my $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
92     my $localitem = TransformMarcToKoha( $dbh, $marcitem, "", 'items' );
93
94     foreach my $itemnumber(@itemnumbers){
95             my $itemdata=GetItem($itemnumber);
96             if ($input->param("del")){
97                     my $return = DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'});
98                     if ($return == 1) {
99                         $deleted_items++;
100                     } else {
101                         $not_deleted_items++;
102                         push @not_deleted, { itemnumber => $itemdata->{'itemnumber'}, barcode => $itemdata->{'barcode'}, title => $itemdata->{'title'}, $return => 1 };
103                     }
104             } else {
105                     my $localmarcitem=Item2Marc($itemdata);
106                     UpdateMarcWith($marcitem,$localmarcitem);
107                     eval{my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($localmarcitem,$itemdata->{biblionumber},$itemnumber)};
108             }
109     }
110     $items_display_hashref=BuildItemsData(@itemnumbers);
111 }
112
113 #
114 #-------------------------------------------------------------------------------
115 # build screen with existing items. and "new" one
116 #-------------------------------------------------------------------------------
117
118 if ($op eq "show"){
119         my $filefh = $input->upload('uploadfile');
120         my $filecontent = $input->param('filecontent');
121         my @notfoundbarcodes;
122
123     my @contentlist;
124     if ($filefh){
125         while (my $content=<$filefh>){
126             chomp $content;
127             push @contentlist, $content;
128         }
129
130         switch ($filecontent) {
131             case "barcode_file" {
132                 foreach my $barcode (@contentlist) {
133
134                     my $itemnumber = GetItemnumberFromBarcode($barcode);
135                     if ($itemnumber) {
136                         push @itemnumbers,$itemnumber;
137                     } else {
138                         push @notfoundbarcodes, $barcode;
139                     }
140                 }
141
142             }
143
144             case "itemid_file" {
145                 @itemnumbers = @contentlist;
146             }
147         }
148     } else {
149        if ( my $list=$input->param('barcodelist')){
150         push my @barcodelist, split(/\s\n/, $list);
151
152         foreach my $barcode (@barcodelist) {
153
154             my $itemnumber = GetItemnumberFromBarcode($barcode);
155             if ($itemnumber) {
156                 push @itemnumbers,$itemnumber;
157             } else {
158                 push @notfoundbarcodes, $barcode;
159             }
160         }
161
162     }
163 }
164         $items_display_hashref=BuildItemsData(@itemnumbers);
165
166 # now, build the item form for entering a new item
167 my @loop_data =();
168 my $i=0;
169 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
170
171 my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
172 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
173
174
175 foreach my $tag (sort keys %{$tagslib}) {
176     # loop through each subfield
177     foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
178         next if subfield_is_koha_internal_p($subfield);
179         next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
180         # barcode and stocknumber are not meant to be batch-modified
181         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.barcode';
182         next if $tagslib->{$tag}->{$subfield}->{'kohafield'} eq 'items.stocknumber';
183         my %subfield_data;
184  
185         my $index_subfield = int(rand(1000000)); 
186         if ($subfield eq '@'){
187             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
188         } else {
189             $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
190         }
191         $subfield_data{tag}        = $tag;
192         $subfield_data{subfield}   = $subfield;
193         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
194     #   $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
195         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
196         $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
197         $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
198         my ($x,$value);
199         $value =~ s/"/&quot;/g;
200         unless ($value) {
201             $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
202             # get today date & replace YYYY, MM, DD if provided in the default value
203             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
204             $value =~ s/YYYY/$year/g;
205             $value =~ s/MM/$month/g;
206             $value =~ s/DD/$day/g;
207         }
208         $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
209         # testing branch value if IndependantBranches.
210
211         my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
212         my $attributes          = qq($attributes_no_value value="$value" );
213
214         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
215         my @authorised_values;
216         my %authorised_lib;
217         # builds list, depending on authorised value...
218   
219         if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
220             foreach my $thisbranch (@$branches) {
221                 push @authorised_values, $thisbranch->{value};
222                 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
223                 $value = $thisbranch->{value} if $thisbranch->{selected};
224             }
225         }
226         elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
227             push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
228             my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
229             $sth->execute;
230             while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
231                 push @authorised_values, $itemtype;
232                 $authorised_lib{$itemtype} = $description;
233             }
234
235           #---- class_sources
236       }
237       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
238           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
239             
240           my $class_sources = GetClassSources();
241           my $default_source = C4::Context->preference("DefaultClassificationSource");
242           
243           foreach my $class_source (sort keys %$class_sources) {
244               next unless $class_sources->{$class_source}->{'used'} or
245                           ($value and $class_source eq $value)      or
246                           ($class_source eq $default_source);
247               push @authorised_values, $class_source;
248               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
249           }
250                   $value = $default_source unless ($value);
251
252           #---- "true" authorised value
253       }
254       else {
255           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
256           $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
257           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
258               push @authorised_values, $value;
259               $authorised_lib{$value} = $lib;
260           }
261       }
262       $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
263           -name     => "field_value",
264           -values   => \@authorised_values,
265           -default  => $value,
266           -labels   => \%authorised_lib,
267           -override => 1,
268           -size     => 1,
269           -multiple => 0,
270           -tabindex => 1,
271           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
272           -class    => "input_marceditor",
273       );
274     # it's a thesaurus / authority field
275     }
276     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
277         $subfield_data{marc_value} = "<input type=\"text\" $attributes />
278             <a href=\"#\" class=\"buttonDot\"
279                 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>
280     ";
281     # it's a plugin field
282     }
283     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
284         # opening plugin
285         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
286         if (do $plugin) {
287                         my $temp;
288             my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
289             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
290             $subfield_data{marc_value} = qq[<input $attributes
291                 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
292                  onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
293                 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
294                 $javascript];
295         } else {
296             warn "Plugin Failed: $plugin";
297             $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
298         }
299     }
300     elsif ( $tag eq '' ) {       # it's an hidden field
301         $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
302     }
303     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
304         $subfield_data{marc_value} = qq(<input type="text" $attributes />);
305     }
306     elsif ( length($value) > 100
307             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
308                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
309             or (C4::Context->preference("marcflavour") eq "MARC21"  and
310                   500 <= $tag && $tag < 600                     )
311           ) {
312         # oversize field (textarea)
313         $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
314     } else {
315         # it's a standard field
316          $subfield_data{marc_value} = "<input $attributes />";
317     }
318 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
319     push (@loop_data, \%subfield_data);
320     $i++
321   }
322 } # -- End foreach tag
323
324
325     # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
326     $template->param(item => \@loop_data);
327     if (@notfoundbarcodes) { 
328         my @notfoundbarcodesloop = map{{barcode=>$_}}@notfoundbarcodes;
329         $template->param(notfoundbarcodes => \@notfoundbarcodesloop);
330     }
331     $nextop="action"
332 } # -- End action="show"
333
334 $template->param(%$items_display_hashref) if $items_display_hashref;
335 $template->param(
336     op      => $nextop,
337     $op => 1,
338 );
339
340 if ($op eq "action") {
341
342     #my @not_deleted_loop = map{{itemnumber=>$_}}@not_deleted;
343
344     $template->param(
345         not_deleted_items => $not_deleted_items,
346         deleted_items => $deleted_items,
347         not_deleted_loop => \@not_deleted 
348     );
349 }
350
351 foreach my $error (@errors) {
352     $template->param($error => 1);
353 }
354 output_html_with_http_headers $input, $cookie, $template->output;
355 exit;
356
357
358 # ---------------- Functions
359
360 sub BuildItemsData{
361         my @itemnumbers=@_;
362                 # now, build existiing item list
363                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
364                 my @big_array;
365                 #---- finds where items.itemnumber is stored
366                 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
367                 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
368                 foreach my $itemnumber (@itemnumbers){
369                         my $itemdata=GetItem($itemnumber);
370                         my $itemmarc=Item2Marc($itemdata);
371                         my %this_row;
372                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
373                                 # loop through each subfield
374                                 if (my $itembranchcode=$field->subfield($branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
375                                                 #verifying rights
376                                                 my $userenv = C4::Context->userenv();
377                                                 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
378                                                                 $this_row{'nomod'}=1;
379                                                 }
380                                 }
381                                 my $tag=$field->tag();
382                                 foreach my $subfield ($field->subfields) {
383                                         my ($subfcode,$subfvalue)=@$subfield;
384                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
385                                                         && $tag        ne $itemtagfield 
386                                                         && $subfcode   ne $itemtagsubfield);
387
388                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
389                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
390                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
391                                                                         $subfcode, $subfvalue, '', $tagslib) 
392                                                                         || $subfvalue;
393                                         }
394
395                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
396                                 }
397                         }
398
399             # grab title, author, and ISBN to identify bib that the item
400             # belongs to in the display
401                         my $biblio=GetBiblioData($$itemdata{biblionumber});
402             $this_row{bibinfo} = join("\n", @$biblio{qw(title author ISBN)});
403
404                         if (%this_row) {
405                                 push(@big_array, \%this_row);
406                         }
407                 }
408                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
409
410                 # now, construct template !
411                 # First, the existing items for display
412                 my @item_value_loop;
413                 my @witnesscodessorted=sort keys %witness;
414                 for my $row ( @big_array ) {
415                         my %row_data;
416                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
417                         $row_data{item_value} = [ @item_fields ];
418                         $row_data{itemnumber} = $row->{itemnumber};
419                         #reporting this_row values
420                         $row_data{'nomod'} = $row->{'nomod'};
421             $row_data{bibinfo} = $row->{bibinfo};
422                         push(@item_value_loop,\%row_data);
423                 }
424                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
425
426         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
427 }
428
429 #BE WARN : it is not the general case 
430 # This function can be OK in the item marc record special case
431 # Where subfield is not repeated
432 # And where we are sure that field should correspond
433 # And $tag>10
434 sub UpdateMarcWith($$){
435   my ($marcfrom,$marcto)=@_;
436   #warn "FROM :",$marcfrom->as_formatted;
437         my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
438         my $fieldfrom=$marcfrom->field($itemtag);
439         my @fields_to=$marcto->field($itemtag);
440     foreach my $subfield ($fieldfrom->subfields()){
441                 foreach my $field_to_update (@fields_to){
442                                 $field_to_update->update($$subfield[0]=>$$subfield[1]) if ($$subfield[1]);
443                 }
444     }
445   #warn "TO edited:",$marcto->as_formatted;
446 }
447
448 sub find_value {
449     my ($tagfield,$insubfield,$record) = @_;
450     my $result;
451     my $indicator;
452     foreach my $field ($record->field($tagfield)) {
453         my @subfields = $field->subfields();
454         foreach my $subfield (@subfields) {
455             if (@$subfield[0] eq $insubfield) {
456                 $result .= @$subfield[1];
457                 $indicator = $field->indicator(1).$field->indicator(2);
458             }
459         }
460     }
461     return($indicator,$result);
462 }
463
464
465