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