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