Merge remote branch 'kc/new/bug_4263' into kcmaster
[koha.git] / cataloguing / additem.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 # Copyright 2004-2010 BibLibre
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use CGI;
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Context;
30 use C4::Koha; # XXX subfield_is_koha_internal_p
31 use C4::Branch; # XXX subfield_is_koha_internal_p
32 use C4::ClassSource;
33 use C4::Dates;
34 use List::MoreUtils qw/any/;
35
36 use MARC::File::XML;
37
38 my $dbh = C4::Context->dbh;
39
40 sub find_value {
41     my ($tagfield,$insubfield,$record) = @_;
42     my $result;
43     my $indicator;
44     foreach my $field ($record->field($tagfield)) {
45         my @subfields = $field->subfields();
46         foreach my $subfield (@subfields) {
47             if (@$subfield[0] eq $insubfield) {
48                 $result .= @$subfield[1];
49                 $indicator = $field->indicator(1).$field->indicator(2);
50             }
51         }
52     }
53     return($indicator,$result);
54 }
55
56 sub get_item_from_barcode {
57     my ($barcode)=@_;
58     my $dbh=C4::Context->dbh;
59     my $result;
60     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
61     $rq->execute($barcode);
62     ($result)=$rq->fetchrow;
63     return($result);
64 }
65
66 sub set_item_default_location {
67     my $itemnumber = shift;
68     if ( C4::Context->preference('NewItemsDefaultLocation') ) {
69         my $item = GetItem( $itemnumber );
70         $item->{'permanent_location'} = $item->{'location'};
71         $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
72         ModItem( $item, undef, $itemnumber);
73     }
74 }
75
76 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
77 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
78 sub _increment_barcode {
79     my ($record, $frameworkcode) = @_;
80     my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
81     unless ($record->field($tagfield)->subfield($tagsubfield)) {
82         my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
83         $sth_barcode->execute;
84         my ($newbarcode) = $sth_barcode->fetchrow;
85         $newbarcode++;
86         # OK, we have the new barcode, now create the entry in MARC record
87         my $fieldItem = $record->field($tagfield);
88         $record->delete_field($fieldItem);
89         $fieldItem->add_subfields($tagsubfield => $newbarcode);
90         $record->insert_fields_ordered($fieldItem);
91     }
92     return $record;
93 }
94
95
96 sub generate_subfield_form {
97         my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $today_iso, $biblionumber, $temp, $loop_data, $i) = @_;
98         
99         my %subfield_data;
100         my $dbh = C4::Context->dbh;        
101         my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
102         
103         my $index_subfield = int(rand(1000000)); 
104         if ($subfieldtag eq '@'){
105             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
106         } else {
107             $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
108         }
109         
110         $subfield_data{tag}        = $tag;
111         $subfield_data{subfield}   = $subfieldtag;
112         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
113         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
114         $subfield_data{mandatory}  = $subfieldlib->{mandatory};
115         $subfield_data{repeatable} = $subfieldlib->{repeatable};
116         
117         $value =~ s/"/&quot;/g;
118         if ( ! defined( $value ) || $value eq '')  {
119             $value = $subfieldlib->{defaultvalue};
120             # get today date & replace YYYY, MM, DD if provided in the default value
121             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
122             $value =~ s/YYYY/$year/g;
123             $value =~ s/MM/$month/g;
124             $value =~ s/DD/$day/g;
125         }
126         
127         $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} < -4));
128         
129         my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
130         if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
131             my $CNtag       = substr($pref_itemcallnumber, 0, 3);
132             my $CNsubfield  = substr($pref_itemcallnumber, 3, 1);
133             my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
134             my $temp2 = $temp->field($CNtag);
135             if ($temp2) {
136                 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
137                 #remove any trailing space incase one subfield is used
138                 $value =~ s/^\s+|\s+$//g;
139             }
140         }
141         
142         my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
143         my $attributes          = qq($attributes_no_value value="$value" );
144         
145         if ( $subfieldlib->{authorised_value} ) {
146             my @authorised_values;
147             my %authorised_lib;
148             # builds list, depending on authorised value...
149             if ( $subfieldlib->{authorised_value} eq "branches" ) {
150                 foreach my $thisbranch (@$branches) {
151                     push @authorised_values, $thisbranch->{value};
152                     $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
153                     $value = $thisbranch->{value} if $thisbranch->{selected};
154                 }
155             }
156             elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
157                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
158                   my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
159                   $sth->execute;
160                   while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
161                       push @authorised_values, $itemtype;
162                       $authorised_lib{$itemtype} = $description;
163                   }
164         
165                   unless ( $value ) {
166                       my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
167                       $itype_sth->execute( $biblionumber );
168                       ( $value ) = $itype_sth->fetchrow_array;
169                   }
170           
171                   #---- class_sources
172             }
173             elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
174                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
175                     
176                   my $class_sources = GetClassSources();
177                   my $default_source = C4::Context->preference("DefaultClassificationSource");
178                   
179                   foreach my $class_source (sort keys %$class_sources) {
180                       next unless $class_sources->{$class_source}->{'used'} or
181                                   ($value and $class_source eq $value)      or
182                                   ($class_source eq $default_source);
183                       push @authorised_values, $class_source;
184                       $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
185                   }
186                           $value = $default_source unless ($value);
187         
188                   #---- "true" authorised value
189             }
190             else {
191                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
192                   $authorised_values_sth->execute( $subfieldlib->{authorised_value} );
193                   while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
194                       push @authorised_values, $value;
195                       $authorised_lib{$value} = $lib;
196                   }
197             }
198
199             $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
200                   -name     => "field_value",
201                   -values   => \@authorised_values,
202                   -default  => $value,
203                   -labels   => \%authorised_lib,
204                   -override => 1,
205                   -size     => 1,
206                   -multiple => 0,
207                   -tabindex => 1,
208                   -id       => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
209                   -class    => "input_marceditor",
210             );
211
212             # it's a thesaurus / authority field
213         }
214         elsif ( $subfieldlib->{authtypecode} ) {
215                 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
216                     <a href=\"#\" class=\"buttonDot\"
217                         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>
218             ";
219             # it's a plugin field
220         }
221         elsif ( $subfieldlib->{value_builder} ) {
222                 # opening plugin
223                 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $subfieldlib->{'value_builder'};
224                 if (do $plugin) {
225                     my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
226                     my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
227                     my $change = index($javascript, 'function Change') > -1 ?
228                         "return Change$function_name($subfield_data{random}, '$subfield_data{id}');" :
229                         'return 1;';
230                     $subfield_data{marc_value} = qq[<input $attributes
231                         onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
232                         onchange=" $change"
233                          onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
234                         <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
235                         $javascript];
236                 } else {
237                     warn "Plugin Failed: $plugin";
238                     $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
239                 }
240         }
241         elsif ( $tag eq '' ) {       # it's an hidden field
242             $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
243         }
244         elsif ( $subfieldlib->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
245             $subfield_data{marc_value} = qq(<input type="text" $attributes />);
246         }
247         elsif ( length($value) > 100
248                     or (C4::Context->preference("marcflavour") eq "UNIMARC" and
249                           300 <= $tag && $tag < 400 && $subfieldtag eq 'a' )
250                     or (C4::Context->preference("marcflavour") eq "MARC21"  and
251                           500 <= $tag && $tag < 600                     )
252                   ) {
253             # oversize field (textarea)
254             $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
255         } else {
256            # it's a standard field
257            $subfield_data{marc_value} = "<input $attributes />";
258         }
259         
260         return \%subfield_data;
261 }
262
263
264 my $input        = new CGI;
265 my $dbh          = C4::Context->dbh;
266 my $error        = $input->param('error');
267 my $biblionumber = $input->param('biblionumber');
268 my $itemnumber   = $input->param('itemnumber');
269 my $op           = $input->param('op');
270
271 my $frameworkcode = &GetFrameworkCode($biblionumber);
272
273 # Defining which userflag is needing according to the framework currently used
274 my $userflags;
275 if (defined $input->param('frameworkcode')) {
276     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
277 }
278
279 if (not defined $userflags) {
280     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
281 }
282
283 my ($template, $loggedinuser, $cookie)
284     = get_template_and_user({template_name => "cataloguing/additem.tmpl",
285                  query => $input,
286                  type => "intranet",
287                  authnotrequired => 0,
288                  flagsrequired => {editcatalogue => $userflags},
289                  debug => 1,
290                  });
291
292
293 my $today_iso = C4::Dates->today('iso');
294 $template->param(today_iso => $today_iso);
295
296 my $tagslib = &GetMarcStructure(1,$frameworkcode);
297 my $record = GetMarcBiblio($biblionumber);
298 my $oldrecord = TransformMarcToKoha($dbh,$record);
299 my $itemrecord;
300 my $nextop="additem";
301 my @errors; # store errors found while checking data BEFORE saving item.
302 #-------------------------------------------------------------------------------
303 if ($op eq "additem") {
304 #-------------------------------------------------------------------------------
305     # rebuild
306     my @tags      = $input->param('tag');
307     my @subfields = $input->param('subfield');
308     my @values    = $input->param('field_value');
309     # build indicator hash.
310     my @ind_tag   = $input->param('ind_tag');
311     my @indicator = $input->param('indicator');
312     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
313     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
314
315     # type of add
316     my $add_submit                 = $input->param('add_submit');
317     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
318     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
319     my $number_of_copies           = $input->param('number_of_copies');
320
321     if (C4::Context->preference('autoBarcode') eq 'incremental') {
322         $record = _increment_barcode($record, $frameworkcode);
323     }
324
325     my $addedolditem = TransformMarcToKoha($dbh,$record);
326
327     # If we have to add or add & duplicate, we add the item
328     if ($add_submit || $add_duplicate_submit) {
329         # check for item barcode # being unique
330         my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
331         push @errors,"barcode_not_unique" if($exist_itemnumber);
332         # if barcode exists, don't create, but report The problem.
333     unless ($exist_itemnumber) {
334             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
335         set_item_default_location($oldbibitemnum);
336     }
337         $nextop = "additem";
338         if ($exist_itemnumber) {
339             $itemrecord = $record;
340         }
341     }
342
343     # If we have to add & duplicate
344     if ($add_duplicate_submit) {
345         $itemrecord = $record;
346         if (C4::Context->preference('autoBarcode') eq 'incremental') {
347             $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
348         }
349         else {
350             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
351             my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
352             my $fieldItem = $itemrecord->field($tagfield);
353             $itemrecord->delete_field($fieldItem);
354             $fieldItem->delete_subfields($tagsubfield);
355             $itemrecord->insert_fields_ordered($fieldItem);
356         }
357     }
358
359     # If we have to add multiple copies
360     if ($add_multiple_copies_submit) {
361
362         use C4::Barcodes;
363         my $barcodeobj = C4::Barcodes->new;
364         my $oldbarcode = $addedolditem->{'barcode'};
365         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
366
367         # If there is a barcode and we can't find him new values, we can't add multiple copies
368         my $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
369         if ($oldbarcode && !$testbarcode) {
370
371             push @errors, "no_next_barcode";
372             $itemrecord = $record;
373
374         } else {
375         # We add each item
376
377             # For the first iteration
378             my $barcodevalue = $oldbarcode;
379             my $exist_itemnumber;
380
381
382             for (my $i = 0; $i < $number_of_copies;) {
383
384                 # If there is a barcode
385                 if ($barcodevalue) {
386
387                     # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
388                     $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
389
390                     # Putting it into the record
391                     if ($barcodevalue) {
392                         $record->field($tagfield)->update($tagsubfield => $barcodevalue);
393                     }
394
395                     # Checking if the barcode already exists
396                     $exist_itemnumber = get_item_from_barcode($barcodevalue);
397                 }
398
399                 # Adding the item
400         if (!$exist_itemnumber) {
401             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
402             set_item_default_location($oldbibitemnum);
403
404             # We count the item only if it was really added
405             # That way, all items are added, even if there was some already existing barcodes
406             # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
407             $i++;
408         }
409
410                 # Preparing the next iteration
411                 $oldbarcode = $barcodevalue;
412             }
413             undef($itemrecord);
414         }
415     }
416
417
418 #-------------------------------------------------------------------------------
419 } elsif ($op eq "edititem") {
420 #-------------------------------------------------------------------------------
421 # retrieve item if exist => then, it's a modif
422     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
423     $nextop = "saveitem";
424 #-------------------------------------------------------------------------------
425 } elsif ($op eq "delitem") {
426 #-------------------------------------------------------------------------------
427     # check that there is no issue on this item before deletion.
428     $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
429     if($error == 1){
430         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
431     }else{
432         push @errors,$error;
433         $nextop="additem";
434     }
435 #-------------------------------------------------------------------------------
436 } elsif ($op eq "delallitems") {
437 #-------------------------------------------------------------------------------
438     my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
439     my $errortest=0;
440     my $itemfail;
441     foreach my $biblioitem (@biblioitems) {
442         my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
443
444         foreach my $item (@$items) {
445             $error =&DelItemCheck( $dbh, $biblionumber, $item->{itemnumber} );
446             $itemfail =$item;
447         if($error == 1){
448             next
449             }
450         else {
451             push @errors,$error;
452             $errortest++
453             }
454         }
455         if($errortest > 0){
456             $nextop="additem";
457         } 
458         else {
459             print $input->redirect("/cgi-bin/koha/catalogue/moredetail.pl?biblionumber=$biblionumber");
460             exit;
461         }
462         }
463 #-------------------------------------------------------------------------------
464 } elsif ($op eq "saveitem") {
465 #-------------------------------------------------------------------------------
466     # rebuild
467     my @tags      = $input->param('tag');
468     my @subfields = $input->param('subfield');
469     my @values    = $input->param('field_value');
470     # build indicator hash.
471     my @ind_tag   = $input->param('ind_tag');
472     my @indicator = $input->param('indicator');
473     # my $itemnumber = $input->param('itemnumber');
474     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
475     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
476     # MARC::Record builded => now, record in DB
477     # warn "R: ".$record->as_formatted;
478     # check that the barcode don't exist already
479     my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
480     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
481     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
482         push @errors,"barcode_not_unique";
483     } else {
484         my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
485         $itemnumber="";
486     }
487     $nextop="additem";
488 }
489
490 #
491 #-------------------------------------------------------------------------------
492 # build screen with existing items. and "new" one
493 #-------------------------------------------------------------------------------
494
495 # now, build existiing item list
496 my $temp = GetMarcBiblio( $biblionumber );
497 my @fields = $temp->fields();
498 #my @fields = $record->fields();
499 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
500 my @big_array;
501 #---- finds where items.itemnumber is stored
502 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
503 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
504
505 foreach my $field (@fields) {
506     next if ( $field->tag() < 10 );
507
508     my @subf = $field->subfields or ();    # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
509     my %this_row;
510     # loop through each subfield
511     my $i = 0;
512     foreach my $subfield (@subf){
513         my $subfieldcode = $subfield->[0];
514         my $subfieldvalue= $subfield->[1];
515
516         next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10 
517                 && ($field->tag() ne $itemtagfield 
518                 && $subfieldcode   ne $itemtagsubfield));
519         $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10);
520                 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10) {
521                     $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
522                 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
523                         $subfieldcode, $subfieldvalue, '', $tagslib) 
524                                                 || $subfieldvalue;
525         }
526
527         if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
528             #verifying rights
529             my $userenv = C4::Context->userenv();
530             unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subfieldvalue))){
531                 $this_row{'nomod'} = 1;
532             }
533         }
534         $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
535     }
536     if (%this_row) {
537         push(@big_array, \%this_row);
538     }
539 }
540
541 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
542 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
543
544 # now, construct template !
545 # First, the existing items for display
546 my @item_value_loop;
547 my @header_value_loop;
548 for my $row ( @big_array ) {
549     my %row_data;
550     my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
551     $row_data{item_value} = [ @item_fields ];
552     $row_data{itemnumber} = $row->{itemnumber};
553     #reporting this_row values
554     $row_data{'nomod'} = $row->{'nomod'};
555     push(@item_value_loop,\%row_data);
556 }
557 foreach my $subfield_code (sort keys(%witness)) {
558     my %header_value;
559     $header_value{header_value} = $witness{$subfield_code};
560     push(@header_value_loop, \%header_value);
561 }
562
563 # now, build the item form for entering a new item
564 my @loop_data =();
565 my $i=0;
566
567 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
568
569 my $onlymine = C4::Context->preference('IndependantBranches') && 
570                C4::Context->userenv                           && 
571                C4::Context->userenv->{flags}!=1               && 
572                C4::Context->userenv->{branch};
573 my $branches = GetBranchesLoop(undef,$onlymine);  # build once ahead of time, instead of multiple times later.
574
575 # We generate form, from actuel record
576 my @fields;
577 if($itemrecord){
578     foreach my $field ($itemrecord->fields()){
579         my $tag = $field->{_tag};
580         foreach my $subfield ( $field->subfields() ){
581
582             my $subfieldtag = $subfield->[0];
583             my $value       = $subfield->[1];
584             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
585
586             next if subfield_is_koha_internal_p($subfieldtag);
587             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
588
589             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);        
590
591             push @fields, "$tag$subfieldtag";
592             push (@loop_data, $subfield_data);
593             $i++;
594                     }
595
596                 }
597             }
598     # and now we add fields that are empty
599
600 foreach my $tag ( keys %{$tagslib}){
601     foreach my $subtag (keys %{$tagslib->{$tag}}){
602         next if subfield_is_koha_internal_p($subtag);
603         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
604         next if any { /^$tag$subtag$/ }  @fields;
605
606         my @values = (undef);
607         @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)->subfield($subtag)));
608         for my $value (@values){
609             my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i); 
610             push (@loop_data, $subfield_data);
611             $i++;
612         } 
613   }
614 }
615 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
616
617 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
618 $template->param( title => $record->title() ) if ($record ne "-1");
619 $template->param(
620     biblionumber => $biblionumber,
621     title        => $oldrecord->{title},
622     author       => $oldrecord->{author},
623     item_loop        => \@item_value_loop,
624     item_header_loop => \@header_value_loop,
625     item             => \@loop_data,
626     itemnumber       => $itemnumber,
627     itemtagfield     => $itemtagfield,
628     itemtagsubfield  => $itemtagsubfield,
629     op      => $nextop,
630     opisadd => ($nextop eq "saveitem") ? 0 : 1,
631     C4::Search::enabled_staff_search_views,
632 );
633 foreach my $error (@errors) {
634     $template->param($error => 1);
635 }
636 output_html_with_http_headers $input, $cookie, $template->output;