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