Merge remote-tracking branch 'origin/new/bug_7548'
[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 my $tagslib = &GetMarcStructure(1,$frameworkcode);
312 my $record = GetMarcBiblio($biblionumber);
313 my $oldrecord = TransformMarcToKoha($dbh,$record);
314 my $itemrecord;
315 my $nextop="additem";
316 my @errors; # store errors found while checking data BEFORE saving item.
317 #-------------------------------------------------------------------------------
318 if ($op eq "additem") {
319 #-------------------------------------------------------------------------------
320     # rebuild
321     my @tags      = $input->param('tag');
322     my @subfields = $input->param('subfield');
323     my @values    = $input->param('field_value');
324     # build indicator hash.
325     my @ind_tag   = $input->param('ind_tag');
326     my @indicator = $input->param('indicator');
327     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
328     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
329
330     # type of add
331     my $add_submit                 = $input->param('add_submit');
332     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
333     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
334     my $number_of_copies           = $input->param('number_of_copies');
335
336     if (C4::Context->preference('autoBarcode') eq 'incremental') {
337         $record = _increment_barcode($record, $frameworkcode);
338     }
339
340     my $addedolditem = TransformMarcToKoha($dbh,$record);
341
342     # If we have to add or add & duplicate, we add the item
343     if ($add_submit || $add_duplicate_submit) {
344         # check for item barcode # being unique
345         my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
346         push @errors,"barcode_not_unique" if($exist_itemnumber);
347         # if barcode exists, don't create, but report The problem.
348     unless ($exist_itemnumber) {
349             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
350         set_item_default_location($oldbibitemnum);
351     }
352         $nextop = "additem";
353         if ($exist_itemnumber) {
354             $itemrecord = $record;
355         }
356     }
357
358     # If we have to add & duplicate
359     if ($add_duplicate_submit) {
360         $itemrecord = $record;
361         if (C4::Context->preference('autoBarcode') eq 'incremental') {
362             $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
363         }
364         else {
365             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
366             my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
367             my $fieldItem = $itemrecord->field($tagfield);
368             $itemrecord->delete_field($fieldItem);
369             $fieldItem->delete_subfields($tagsubfield);
370             $itemrecord->insert_fields_ordered($fieldItem);
371         }
372     }
373
374     # If we have to add multiple copies
375     if ($add_multiple_copies_submit) {
376
377         use C4::Barcodes;
378         my $barcodeobj = C4::Barcodes->new;
379         my $oldbarcode = $addedolditem->{'barcode'};
380         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
381
382         # If there is a barcode and we can't find him new values, we can't add multiple copies
383         my $testbarcode;
384         $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             my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
484             my $views = { C4::Search::enabled_staff_search_views };
485             if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
486                 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber");
487             } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
488                 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber");
489             } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
490                 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber");
491             } else {
492                 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber");
493             }
494             exit;
495         }
496         }
497 #-------------------------------------------------------------------------------
498 } elsif ($op eq "saveitem") {
499 #-------------------------------------------------------------------------------
500     # rebuild
501     my @tags      = $input->param('tag');
502     my @subfields = $input->param('subfield');
503     my @values    = $input->param('field_value');
504     # build indicator hash.
505     my @ind_tag   = $input->param('ind_tag');
506     my @indicator = $input->param('indicator');
507     # my $itemnumber = $input->param('itemnumber');
508     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
509     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
510     # MARC::Record builded => now, record in DB
511     # warn "R: ".$record->as_formatted;
512     # check that the barcode don't exist already
513     my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
514     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
515     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
516         push @errors,"barcode_not_unique";
517     } else {
518         ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
519         $itemnumber="";
520     }
521     $nextop="additem";
522 } elsif ($op eq "delinkitem"){
523     my $analyticfield = '773';
524         if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC'){
525         $analyticfield = '773';
526     } elsif ($marcflavour eq 'UNIMARC') {
527         $analyticfield = '461';
528     }
529     foreach my $field ($record->field($analyticfield)){
530         if ($field->subfield('9') eq $hostitemnumber){
531             $record->delete_field($field);
532             last;
533         }
534     }
535         my $modbibresult = ModBiblio($record, $biblionumber,'');
536 }
537
538 #
539 #-------------------------------------------------------------------------------
540 # build screen with existing items. and "new" one
541 #-------------------------------------------------------------------------------
542
543 # now, build existiing item list
544 my $temp = GetMarcBiblio( $biblionumber );
545 #my @fields = $record->fields();
546
547
548 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
549 my @big_array;
550 #---- finds where items.itemnumber is stored
551 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
552 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
553 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
554 my @fields = $temp->fields();
555
556
557 my @hostitemnumbers;
558 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
559     my $analyticfield = '773';
560     if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC') {
561         $analyticfield = '773';
562     } elsif ($marcflavour eq 'UNIMARC') {
563         $analyticfield = '461';
564     }
565     foreach my $hostfield ($temp->field($analyticfield)){
566         if ($hostfield->subfield('0')){
567             my $hostrecord = GetMarcBiblio($hostfield->subfield('0'), 1);
568             my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostfield->subfield('0')) );
569             foreach my $hostitem ($hostrecord->field($itemfield)){
570                 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
571                     push (@fields, $hostitem);
572                     push (@hostitemnumbers, $hostfield->subfield('9'));
573                 }
574             }
575         }
576     }
577 }
578
579
580 foreach my $field (@fields) {
581     next if ( $field->tag() < 10 );
582
583     my @subf = $field->subfields or ();    # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
584     my %this_row;
585     # loop through each subfield
586     my $i = 0;
587     foreach my $subfield (@subf){
588         my $subfieldcode = $subfield->[0];
589         my $subfieldvalue= $subfield->[1];
590
591         next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10 
592                 && ($field->tag() ne $itemtagfield 
593                 && $subfieldcode   ne $itemtagsubfield));
594         $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10);
595                 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10) {
596                     $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
597                 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
598                         $subfieldcode, $subfieldvalue, '', $tagslib) 
599                                                 || $subfieldvalue;
600         }
601
602         if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
603             #verifying rights
604             my $userenv = C4::Context->userenv();
605             unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subfieldvalue))){
606                 $this_row{'nomod'} = 1;
607             }
608         }
609         $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
610
611         if ( C4::Context->preference('EasyAnalyticalRecords') ) {
612             foreach my $hostitemnumber (@hostitemnumbers){
613                 if ($this_row{itemnumber} eq $hostitemnumber){
614                         $this_row{hostitemflag} = 1;
615                         $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
616                         last;
617                 }
618             }
619
620 #           my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
621 #           if ($countanalytics > 0){
622 #                $this_row{countanalytics} = $countanalytics;
623 #           }
624         }
625
626     }
627     if (%this_row) {
628         push(@big_array, \%this_row);
629     }
630 }
631
632 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
633 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
634
635 # now, construct template !
636 # First, the existing items for display
637 my @item_value_loop;
638 my @header_value_loop;
639 for my $row ( @big_array ) {
640     my %row_data;
641     my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
642     $row_data{item_value} = [ @item_fields ];
643     $row_data{itemnumber} = $row->{itemnumber};
644     #reporting this_row values
645     $row_data{'nomod'} = $row->{'nomod'};
646     $row_data{'hostitemflag'} = $row->{'hostitemflag'};
647     $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
648 #       $row_data{'countanalytics'} = $row->{'countanalytics'};
649     push(@item_value_loop,\%row_data);
650 }
651 foreach my $subfield_code (sort keys(%witness)) {
652     my %header_value;
653     $header_value{header_value} = $witness{$subfield_code};
654     push(@header_value_loop, \%header_value);
655 }
656
657 # now, build the item form for entering a new item
658 my @loop_data =();
659 my $i=0;
660
661 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
662
663 my $onlymine = C4::Context->preference('IndependantBranches') && 
664                C4::Context->userenv                           && 
665                C4::Context->userenv->{flags}!=1               && 
666                C4::Context->userenv->{branch};
667 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
668 my $branches = GetBranchesLoop($branch,$onlymine);  # build once ahead of time, instead of multiple times later.
669
670 # We generate form, from actuel record
671 @fields = ();
672 if($itemrecord){
673     foreach my $field ($itemrecord->fields()){
674         my $tag = $field->{_tag};
675         foreach my $subfield ( $field->subfields() ){
676
677             my $subfieldtag = $subfield->[0];
678             my $value       = $subfield->[1];
679             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
680
681             next if subfield_is_koha_internal_p($subfieldtag);
682             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
683
684             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);        
685
686             push @fields, "$tag$subfieldtag";
687             push (@loop_data, $subfield_data);
688             $i++;
689                     }
690
691                 }
692             }
693     # and now we add fields that are empty
694
695 foreach my $tag ( keys %{$tagslib}){
696     foreach my $subtag (keys %{$tagslib->{$tag}}){
697         next if subfield_is_koha_internal_p($subtag);
698         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
699         next if any { /^$tag$subtag$/ }  @fields;
700
701         my @values = (undef);
702         @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)->subfield($subtag)));
703         for my $value (@values){
704             my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i); 
705             push (@loop_data, $subfield_data);
706             $i++;
707         } 
708   }
709 }
710 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
711
712 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
713 $template->param( title => $record->title() ) if ($record ne "-1");
714 $template->param(
715     biblionumber => $biblionumber,
716     title        => $oldrecord->{title},
717     author       => $oldrecord->{author},
718     item_loop        => \@item_value_loop,
719     item_header_loop => \@header_value_loop,
720     item             => \@loop_data,
721     itemnumber       => $itemnumber,
722     itemtagfield     => $itemtagfield,
723     itemtagsubfield  => $itemtagsubfield,
724     op      => $nextop,
725     opisadd => ($nextop eq "saveitem") ? 0 : 1,
726     C4::Search::enabled_staff_search_views,
727 );
728
729 if ($frameworkcode eq 'FA'){
730     $template->{VARS}->{'borrowernumber'}=$input->param('borrowernumber');
731     $template->{VARS}->{'barcode'}=$input->param('barcode');
732     $template->{VARS}->{'stickyduedate'}=$input->param('stickduedate');
733     $template->{VARS}->{'duedatespec'}=$input->param('duedatespec');
734 }    
735
736 foreach my $error (@errors) {
737     $template->param($error => 1);
738 }
739 output_html_with_http_headers $input, $cookie, $template->output;