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