Bug 2919 -- fix value_builder plugins for dateaccessioned, barcode
[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     $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
137     if($error == 1){
138         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
139                 exit;
140     }else{
141         push @errors,$error;
142         $nextop="additem";
143     }
144 #-------------------------------------------------------------------------------
145 } elsif ($op eq "delallitems") {
146 #-------------------------------------------------------------------------------
147     my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
148     foreach my $biblioitem (@biblioitems){
149         my $items = &GetItemsByBiblioitemnumber($biblioitem->{biblioitemnumber});
150
151         foreach my $item (@$items){
152             &DelItem($dbh,$biblionumber,$item->{itemnumber});
153         }
154     }
155     print $input->redirect("/cgi-bin/koha/catalogue/moredetail.pl?biblionumber=$biblionumber");
156         exit;
157 #-------------------------------------------------------------------------------
158 } elsif ($op eq "saveitem") {
159 #-------------------------------------------------------------------------------
160     # rebuild
161     my @tags      = $input->param('tag');
162     my @subfields = $input->param('subfield');
163     my @values    = $input->param('field_value');
164     # build indicator hash.
165     my @ind_tag   = $input->param('ind_tag');
166     my @indicator = $input->param('indicator');
167     # my $itemnumber = $input->param('itemnumber');
168     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
169     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
170     # MARC::Record builded => now, record in DB
171     # warn "R: ".$record->as_formatted;
172     # check that the barcode don't exist already
173     my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
174     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
175     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
176         push @errors,"barcode_not_unique";
177     } else {
178         my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
179         $itemnumber="";
180     }
181     $nextop="additem";
182 }
183
184 #
185 #-------------------------------------------------------------------------------
186 # build screen with existing items. and "new" one
187 #-------------------------------------------------------------------------------
188
189 # now, build existiing item list
190 my $temp = GetMarcBiblio( $biblionumber );
191 my @fields = $temp->fields();
192 #my @fields = $record->fields();
193 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
194 my @big_array;
195 #---- finds where items.itemnumber is stored
196 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
197 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
198
199 foreach my $field (@fields) {
200     next if ($field->tag()<10);
201     my @subf = $field->subfields;
202     (defined @subf) or @subf = ();
203     my %this_row;
204 # loop through each subfield
205     for my $i (0..$#subf) {
206         next if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab} ne 10 
207                 && ($field->tag() ne $itemtagfield 
208                 && $subf[$i][0]   ne $itemtagsubfield));
209
210         $witness{$subf[$i][0]} = $tagslib->{$field->tag()}->{$subf[$i][0]}->{lib} if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  eq 10);
211                 if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  eq 10) {
212                 $this_row{$subf[$i][0]}=GetAuthorisedValueDesc( $field->tag(),
213                         $subf[$i][0], $subf[$i][1], '', $tagslib) 
214                                                 || $subf[$i][1];
215                 }
216
217         if (($field->tag eq $branchtagfield) && ($subf[$i][$0] eq $branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
218             #verifying rights
219             my $userenv = C4::Context->userenv();
220             unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subf[$i][1]))){
221                     $this_row{'nomod'}=1;
222             }
223         }
224         $this_row{itemnumber} = $subf[$i][1] if ($field->tag() eq $itemtagfield && $subf[$i][0] eq $itemtagsubfield);
225     }
226     if (%this_row) {
227         push(@big_array, \%this_row);
228     }
229 }
230 #fill big_row with missing data
231 foreach my $subfield_code  (keys(%witness)) {
232     for (my $i=0;$i<=$#big_array;$i++) {
233         $big_array[$i]{$subfield_code}="&nbsp;" unless ($big_array[$i]{$subfield_code});
234     }
235 }
236 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
237 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
238
239 # now, construct template !
240 # First, the existing items for display
241 my @item_value_loop;
242 my @header_value_loop;
243 for (my $i=0;$i<=$#big_array; $i++) {
244     my $items_data;
245     foreach my $subfield_code (sort keys(%witness)) {
246         $items_data .="<td>".$big_array[$i]{$subfield_code}."</td>";
247     }
248     my %row_data;
249     $items_data =~ s/"/&quot;/g;
250     $row_data{item_value} = $items_data;
251     $row_data{itemnumber} = $big_array[$i]->{itemnumber};
252     #reporting this_row values
253     $row_data{'nomod'}    = $big_array[$i]{'nomod'};
254     push(@item_value_loop,\%row_data);
255 }
256 foreach my $subfield_code (sort keys(%witness)) {
257     my %header_value;
258     $header_value{header_value} = $witness{$subfield_code};
259     push(@header_value_loop, \%header_value);
260 }
261
262 # now, build the item form for entering a new item
263 my @loop_data =();
264 my $i=0;
265 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
266
267 my $onlymine = C4::Context->preference('IndependantBranches') && 
268                C4::Context->userenv                           && 
269                C4::Context->userenv->{flags}!=1               && 
270                C4::Context->userenv->{branch};
271 my $branches = GetBranches($onlymine);  # build once ahead of time, instead of multiple times later.
272
273 foreach my $tag (sort keys %{$tagslib}) {
274 # loop through each subfield
275   foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
276     next if subfield_is_koha_internal_p($subfield);
277     next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
278     my %subfield_data;
279  
280     my $index_subfield = int(rand(1000000)); 
281     if ($subfield eq '@'){
282         $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
283     } else {
284         $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
285     }
286     $subfield_data{tag}        = $tag;
287     $subfield_data{subfield}   = $subfield;
288     $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
289 #   $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
290     $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
291     $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
292     $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
293     my ($x,$value);
294     ($x,$value) = find_value($tag,$subfield,$itemrecord) if ($itemrecord);
295     $value =~ s/"/&quot;/g;
296     unless ($value) {
297         $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
298         # get today date & replace YYYY, MM, DD if provided in the default value
299         my ( $year, $month, $day ) = split ',', $today_iso;
300         $value =~ s/YYYY/$year/g;
301         $value =~ s/MM/$month/g;
302         $value =~ s/DD/$day/g;
303     }
304     $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
305     # testing branch value if IndependantBranches.
306     # my $test = (C4::Context->preference("IndependantBranches")) &&
307     #          ($tag eq $branchtagfield) && ($subfield eq $branchtagsubfield) &&
308     #          (C4::Context->userenv->{flags} != 1) && ($value) && ($value ne C4::Context->userenv->{branch}) ;
309     # $test and print $input->redirect(".pl?biblionumber=$biblionumber") and exit;
310         # search for itemcallnumber if applicable
311     my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
312     if (!$value && $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
313         my $CNtag       = substr($pref_itemcallnumber, 0, 3);
314         my $CNsubfield  = substr($pref_itemcallnumber, 3, 1);
315         my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
316         my $temp2 = $temp->field($CNtag);
317         if ($temp2) {
318             $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
319             #remove any trailing space incase one subfield is used
320             $value =~ s/^\s+|\s+$//g;
321         }
322     }
323
324     my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
325     my $attributes          = qq($attributes_no_value value="$value" );
326     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
327       my @authorised_values;
328       my %authorised_lib;
329       # builds list, depending on authorised value...
330   
331       if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
332           foreach my $thisbranch ( sort keys %$branches ) {
333               push @authorised_values, $thisbranch;
334               $authorised_lib{$thisbranch} = $branches->{$thisbranch}->{'branchname'};
335           }
336       }
337       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
338           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
339           my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
340           $sth->execute;
341           my $itemtype;     # FIXME: double declaration of $itemtype
342           while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
343               push @authorised_values, $itemtype;
344               $authorised_lib{$itemtype} = $description;
345           }
346           $value = $itemtype unless ($value);
347       }
348       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
349           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
350             
351           my $class_sources = GetClassSources();
352           my $default_source = C4::Context->preference("DefaultClassificationSource");
353           
354           foreach my $class_source (sort keys %$class_sources) {
355               next unless $class_sources->{$class_source}->{'used'} or
356                           ($value and $class_source eq $value)      or
357                           ($class_source eq $default_source);
358               push @authorised_values, $class_source;
359               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
360           }
361                   $value = $default_source unless ($value);
362
363           #---- "true" authorised value
364       }
365       else {
366           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
367           $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
368           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
369               push @authorised_values, $value;
370               $authorised_lib{$value} = $lib;
371           }
372       }
373       $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
374           -name     => "field_value",
375           -values   => \@authorised_values,
376           -default  => $value,
377           -labels   => \%authorised_lib,
378           -override => 1,
379           -size     => 1,
380           -multiple => 0,
381           -tabindex => 1,
382           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
383           -class    => "input_marceditor",
384       );
385     # it's a thesaurus / authority field
386     }
387     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
388         $subfield_data{marc_value} = "<input type=\"text\" $attributes />
389             <a href=\"#\" class=\"buttonDot\"
390                 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>
391     ";
392     # it's a plugin field
393     }
394     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
395         # opening plugin
396         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
397         if (do $plugin) {
398             my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
399             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
400             $subfield_data{marc_value} = qq[<input $attributes
401                 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
402                  onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
403                 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
404                 $javascript];
405         } else {
406             warn "Plugin Failed: $plugin";
407             $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
408         }
409     }
410     elsif ( $tag eq '' ) {       # it's an hidden field
411         $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
412     }
413     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
414         $subfield_data{marc_value} = qq(<input type="text" $attributes />);
415     }
416     elsif ( length($value) > 100
417             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
418                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
419             or (C4::Context->preference("marcflavour") eq "MARC21"  and
420                   500 <= $tag && $tag < 600                     )
421           ) {
422         # oversize field (textarea)
423         $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
424     } else {
425         # it's a standard field
426          $subfield_data{marc_value} = "<input $attributes />";
427     }
428 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
429     push (@loop_data, \%subfield_data);
430     $i++
431   }
432 }
433
434 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
435 $template->param( title => $record->title() ) if ($record ne "-1");
436 $template->param(
437     biblionumber => $biblionumber,
438     title        => $oldrecord->{title},
439     author       => $oldrecord->{author},
440     item_loop        => \@item_value_loop,
441     item_header_loop => \@header_value_loop,
442     item             => \@loop_data,
443     itemnumber       => $itemnumber,
444     itemtagfield     => $itemtagfield,
445     itemtagsubfield  => $itemtagsubfield,
446     op      => $nextop,
447     opisadd => ($nextop eq "saveitem") ? 0 : 1,
448 );
449 foreach my $error (@errors) {
450     $template->param($error => 1);
451 }
452 output_html_with_http_headers $input, $cookie, $template->output;