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