fix crash introduced in previous patch
[koha.git] / cataloguing / additem.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
33 use MARC::File::XML;
34
35 sub find_value {
36     my ($tagfield,$insubfield,$record) = @_;
37     my $result;
38     my $indicator;
39     foreach my $field ($record->field($tagfield)) {
40         my @subfields = $field->subfields();
41         foreach my $subfield (@subfields) {
42             if (@$subfield[0] eq $insubfield) {
43                 $result .= @$subfield[1];
44                 $indicator = $field->indicator(1).$field->indicator(2);
45             }
46         }
47     }
48     return($indicator,$result);
49 }
50
51 sub get_item_from_barcode {
52     my ($barcode)=@_;
53     my $dbh=C4::Context->dbh;
54     my $result;
55     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
56     $rq->execute($barcode);
57     ($result)=$rq->fetchrow;
58     return($result);
59 }
60
61 my $input = new CGI;
62 my $dbh = C4::Context->dbh;
63 my $error        = $input->param('error');
64 my $biblionumber = $input->param('biblionumber');
65 my $itemnumber   = $input->param('itemnumber');
66 my $op           = $input->param('op');
67
68 my ($template, $loggedinuser, $cookie)
69     = get_template_and_user({template_name => "cataloguing/additem.tmpl",
70                  query => $input,
71                  type => "intranet",
72                  authnotrequired => 0,
73                  flagsrequired => {editcatalogue => 1},
74                  debug => 1,
75                  });
76
77 my $frameworkcode = &GetFrameworkCode($biblionumber);
78
79 my $today_iso = C4::Dates->today('iso');
80 $template->param(today_iso => $today_iso);
81
82 my $tagslib = &GetMarcStructure(1,$frameworkcode);
83 my $record = GetMarcBiblio($biblionumber);
84 my $oldrecord = TransformMarcToKoha($dbh,$record);
85 my $itemrecord;
86 my $nextop="additem";
87 my @errors; # store errors found while checking data BEFORE saving item.
88 #-------------------------------------------------------------------------------
89 if ($op eq "additem") {
90 #-------------------------------------------------------------------------------
91     # rebuild
92     my @tags      = $input->param('tag');
93     my @subfields = $input->param('subfield');
94     my @values    = $input->param('field_value');
95     # build indicator hash.
96     my @ind_tag   = $input->param('ind_tag');
97     my @indicator = $input->param('indicator');
98     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
99     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
100     # if autoBarcode is set to 'incremental', calculate barcode...
101         # NOTE: This code is subject to change in 3.2 with the implemenation of ajax based autobarcode code
102         # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
103     if (C4::Context->preference('autoBarcode') eq 'incremental') {
104         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
105         unless ($record->field($tagfield)->subfield($tagsubfield)) {
106             my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
107             $sth_barcode->execute;
108             my ($newbarcode) = $sth_barcode->fetchrow;
109             $newbarcode++;
110             # OK, we have the new barcode, now create the entry in MARC record
111             my $fieldItem = $record->field($tagfield);
112             $record->delete_field($fieldItem);
113             $fieldItem->add_subfields($tagsubfield => $newbarcode);
114             $record->insert_fields_ordered($fieldItem);
115         }
116     }
117 # check for item barcode # being unique
118     my $addedolditem = TransformMarcToKoha($dbh,$record);
119     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
120     push @errors,"barcode_not_unique" if($exist_itemnumber);
121     # if barcode exists, don't create, but report The problem.
122     my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber) unless ($exist_itemnumber);
123     $nextop = "additem";
124     if ($exist_itemnumber) {
125         $itemrecord = $record;
126     }
127 #-------------------------------------------------------------------------------
128 } elsif ($op eq "edititem") {
129 #-------------------------------------------------------------------------------
130 # retrieve item if exist => then, it's a modif
131     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
132     $nextop = "saveitem";
133 #-------------------------------------------------------------------------------
134 } elsif ($op eq "delitem") {
135 #-------------------------------------------------------------------------------
136     # check that there is no issue on this item before deletion.
137     my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
138     $sth->execute($itemnumber);
139     my $onloan=$sth->fetchrow;
140         $sth->finish();
141     $nextop="additem";
142     if ($onloan){
143         push @errors,"book_on_loan";
144     } else {
145                 # check it doesnt have a waiting reserve
146                 $sth=$dbh->prepare("SELECT * FROM reserves WHERE found = 'W' AND itemnumber = ?");
147                 $sth->execute($itemnumber);
148                 my $reserve=$sth->fetchrow;
149                 unless ($reserve){
150                         &DelItem($dbh,$biblionumber,$itemnumber);
151                         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
152             exit;
153                 }
154         push @errors,"book_reserved";
155     }
156 #-------------------------------------------------------------------------------
157 } elsif ($op eq "saveitem") {
158 #-------------------------------------------------------------------------------
159     # rebuild
160     my @tags      = $input->param('tag');
161     my @subfields = $input->param('subfield');
162     my @values    = $input->param('field_value');
163     # build indicator hash.
164     my @ind_tag   = $input->param('ind_tag');
165     my @indicator = $input->param('indicator');
166     # my $itemnumber = $input->param('itemnumber');
167     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
168     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
169     # MARC::Record builded => now, record in DB
170     # warn "R: ".$record->as_formatted;
171     # check that the barcode don't exist already
172     my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
173     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
174     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
175         push @errors,"barcode_not_unique";
176     } else {
177         my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
178         $itemnumber="";
179     }
180     $nextop="additem";
181 }
182
183 #
184 #-------------------------------------------------------------------------------
185 # build screen with existing items. and "new" one
186 #-------------------------------------------------------------------------------
187
188 # now, build existiing item list
189 my $temp = GetMarcBiblio( $biblionumber );
190 my @fields = $temp->fields();
191 #my @fields = $record->fields();
192 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
193 my @big_array;
194 #---- finds where items.itemnumber is stored
195 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
196 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
197
198 foreach my $field (@fields) {
199     next if ($field->tag()<10);
200     my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
201     my %this_row;
202 # loop through each subfield
203     for my $i (0..$#subf) {
204         next if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab} ne 10 
205                 && ($field->tag() ne $itemtagfield 
206                 && $subf[$i][0]   ne $itemtagsubfield));
207
208         $witness{$subf[$i][0]} = $tagslib->{$field->tag()}->{$subf[$i][0]}->{lib} if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  eq 10);
209                 if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  eq 10) {
210                 $this_row{$subf[$i][0]}=GetAuthorisedValueDesc( $field->tag(),
211                         $subf[$i][0], $subf[$i][1], '', $tagslib) 
212                                                 || $subf[$i][1];
213                 }
214
215         if (($field->tag eq $branchtagfield) && ($subf[$i][$0] eq $branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
216             #verifying rights
217             my $userenv = C4::Context->userenv();
218             unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subf[$i][1]))){
219                     $this_row{'nomod'}=1;
220             }
221         }
222         $this_row{itemnumber} = $subf[$i][1] if ($field->tag() eq $itemtagfield && $subf[$i][0] eq $itemtagsubfield);
223     }
224     if (%this_row) {
225         push(@big_array, \%this_row);
226     }
227 }
228
229 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
230 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
231
232 # now, construct template !
233 # First, the existing items for display
234 my @item_value_loop;
235 my @header_value_loop;
236 for my $row ( @big_array ) {
237     my %row_data;
238     my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
239     $row_data{item_value} = [ @item_fields ];
240     $row_data{itemnumber} = $row->{itemnumber};
241     #reporting this_row values
242     $row_data{'nomod'} = $row->{'nomod'};
243     push(@item_value_loop,\%row_data);
244 }
245 foreach my $subfield_code (sort keys(%witness)) {
246     my %header_value;
247     $header_value{header_value} = $witness{$subfield_code};
248     push(@header_value_loop, \%header_value);
249 }
250
251 # now, build the item form for entering a new item
252 my @loop_data =();
253 my $i=0;
254 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
255
256 my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
257 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
258
259 foreach my $tag (sort keys %{$tagslib}) {
260 # loop through each subfield
261   foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
262     next if subfield_is_koha_internal_p($subfield);
263     next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
264     my %subfield_data;
265  
266     my $index_subfield = int(rand(1000000)); 
267     if ($subfield eq '@'){
268         $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
269     } else {
270         $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
271     }
272     $subfield_data{tag}        = $tag;
273     $subfield_data{subfield}   = $subfield;
274     $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
275 #   $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
276     $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
277     $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
278     $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
279     my ($x,$value);
280     ($x,$value) = find_value($tag,$subfield,$itemrecord) if ($itemrecord);
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;
289     }
290     $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
291     # testing branch value if IndependantBranches.
292     if (!$value && $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
293         my $CNtag       = substr($pref_itemcallnumber, 0, 3);
294         my $CNsubfield  = substr($pref_itemcallnumber, 3, 1);
295         my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
296         my $temp2 = $temp->field($CNtag);
297         if ($temp2) {
298             $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
299             #remove any trailing space incase one subfield is used
300             $value =~ s/^\s+|\s+$//g;
301         }
302     }
303
304     my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
305     my $attributes          = qq($attributes_no_value value="$value" );
306     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
307       my @authorised_values;
308       my %authorised_lib;
309       # builds list, depending on authorised value...
310   
311       if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
312           foreach my $thisbranch (@$branches) {
313               push @authorised_values, $thisbranch->{value};
314               $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
315               $value = $thisbranch->{value} if $thisbranch->{selected};
316           }
317       }
318       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
319           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
320           my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
321           $sth->execute;
322           while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
323               push @authorised_values, $itemtype;
324               $authorised_lib{$itemtype} = $description;
325           }
326
327           unless ( $value ) {
328               my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
329               $itype_sth->execute( $biblionumber );
330               ( $value ) = $itype_sth->fetchrow_array;
331           }
332   
333           #---- class_sources
334       }
335       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
336           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
337             
338           my $class_sources = GetClassSources();
339           my $default_source = C4::Context->preference("DefaultClassificationSource");
340           
341           foreach my $class_source (sort keys %$class_sources) {
342               next unless $class_sources->{$class_source}->{'used'} or
343                           ($value and $class_source eq $value)      or
344                           ($class_source eq $default_source);
345               push @authorised_values, $class_source;
346               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
347           }
348                   $value = $default_source unless ($value);
349
350           #---- "true" authorised value
351       }
352       else {
353           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
354           $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
355           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
356               push @authorised_values, $value;
357               $authorised_lib{$value} = $lib;
358           }
359       }
360       $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
361           -name     => "field_value",
362           -values   => \@authorised_values,
363           -default  => $value,
364           -labels   => \%authorised_lib,
365           -override => 1,
366           -size     => 1,
367           -multiple => 0,
368           -tabindex => 1,
369           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
370           -class    => "input_marceditor",
371       );
372     # it's a thesaurus / authority field
373     }
374     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
375         $subfield_data{marc_value} = "<input type=\"text\" $attributes />
376             <a href=\"#\" class=\"buttonDot\"
377                 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>
378     ";
379     # it's a plugin field
380     }
381     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
382         # opening plugin
383         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
384         if (do $plugin) {
385             my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
386             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
387             $subfield_data{marc_value} = qq[<input $attributes
388                 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
389                  onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
390                 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
391                 $javascript];
392         } else {
393             warn "Plugin Failed: $plugin";
394             $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
395         }
396     }
397     elsif ( $tag eq '' ) {       # it's an hidden field
398         $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
399     }
400     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
401         $subfield_data{marc_value} = qq(<input type="text" $attributes />);
402     }
403     elsif ( length($value) > 100
404             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
405                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
406             or (C4::Context->preference("marcflavour") eq "MARC21"  and
407                   500 <= $tag && $tag < 600                     )
408           ) {
409         # oversize field (textarea)
410         $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
411     } else {
412         # it's a standard field
413          $subfield_data{marc_value} = "<input $attributes />";
414     }
415 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
416     push (@loop_data, \%subfield_data);
417     $i++
418   }
419 }
420
421 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
422 $template->param( title => $record->title() ) if ($record ne "-1");
423 $template->param(
424     biblionumber => $biblionumber,
425     title        => $oldrecord->{title},
426     author       => $oldrecord->{author},
427     item_loop        => \@item_value_loop,
428     item_header_loop => \@header_value_loop,
429     item             => \@loop_data,
430     itemnumber       => $itemnumber,
431     itemtagfield     => $itemtagfield,
432     itemtagsubfield  => $itemtagsubfield,
433     op      => $nextop,
434     opisadd => ($nextop eq "saveitem") ? 0 : 1,
435 );
436 foreach my $error (@errors) {
437     $template->param($error => 1);
438 }
439 output_html_with_http_headers $input, $cookie, $template->output;