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