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