Bug 27526: Remove ModItemFromMarc from additem
[koha-ffzg.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
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 use Modern::Perl;
23
24 use CGI qw ( -utf8 );
25 use C4::Auth qw( get_template_and_user haspermission );
26 use C4::Output qw( output_and_exit_if_error output_and_exit output_html_with_http_headers );
27 use C4::Biblio qw(
28     GetAuthorisedValueDesc
29     GetFrameworkCode
30     GetMarcBiblio
31     GetMarcFromKohaField
32     GetMarcStructure
33     IsMarcStructureInternal
34     ModBiblio
35     TransformHtmlToXml
36     TransformMarcToKoha
37 );
38 use C4::Items qw( AddItemFromMarc ModItemFromMarc );
39 use C4::Context;
40 use C4::Circulation qw( LostItem );
41 use C4::Koha qw( GetAuthorisedValues );
42 use C4::ClassSource qw( GetClassSources GetClassSource );
43 use Koha::DateUtils qw( dt_from_string );
44 use Koha::Items;
45 use Koha::ItemTypes;
46 use Koha::Libraries;
47 use Koha::Patrons;
48 use Koha::SearchEngine::Indexer;
49 use List::MoreUtils qw( any );
50 use C4::Search qw( enabled_staff_search_views );
51 use Storable qw( freeze thaw );
52 use URI::Escape qw( uri_escape_utf8 );
53 use C4::Members;
54
55 use MARC::File::XML;
56 use URI::Escape qw( uri_escape_utf8 );
57 use MIME::Base64 qw( decode_base64url encode_base64url );
58
59 our $dbh = C4::Context->dbh;
60
61 sub find_value {
62     my ($tagfield,$insubfield,$record) = @_;
63     my $result;
64     my $indicator;
65     foreach my $field ($record->field($tagfield)) {
66         my @subfields = $field->subfields();
67         foreach my $subfield (@subfields) {
68             if (@$subfield[0] eq $insubfield) {
69                 $result .= @$subfield[1];
70                 $indicator = $field->indicator(1).$field->indicator(2);
71             }
72         }
73     }
74     return($indicator,$result);
75 }
76
77 sub get_item_from_barcode {
78     my ($barcode)=@_;
79     my $dbh=C4::Context->dbh;
80     my $result;
81     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
82     $rq->execute($barcode);
83     ($result)=$rq->fetchrow;
84     return($result);
85 }
86
87 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
88 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
89 sub _increment_barcode {
90     my ($record, $frameworkcode) = @_;
91     my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
92     unless ($record->field($tagfield)->subfield($tagsubfield)) {
93         my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
94         $sth_barcode->execute;
95         my ($newbarcode) = $sth_barcode->fetchrow;
96         $newbarcode++;
97         # OK, we have the new barcode, now create the entry in MARC record
98         my $fieldItem = $record->field($tagfield);
99         $record->delete_field($fieldItem);
100         $fieldItem->add_subfields($tagsubfield => $newbarcode);
101         $record->insert_fields_ordered($fieldItem);
102     }
103     return $record;
104 }
105
106
107 sub generate_subfield_form {
108         my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition, $item) = @_;
109   
110         my $frameworkcode = &GetFrameworkCode($biblionumber);
111
112         my %subfield_data;
113         my $dbh = C4::Context->dbh;
114         
115         my $index_subfield = int(rand(1000000)); 
116         if ($subfieldtag eq '@'){
117             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
118         } else {
119             $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
120         }
121         
122         $subfield_data{tag}        = $tag;
123         $subfield_data{subfield}   = $subfieldtag;
124         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
125         $subfield_data{mandatory}  = $subfieldlib->{mandatory};
126         $subfield_data{important}  = $subfieldlib->{important};
127         $subfield_data{repeatable} = $subfieldlib->{repeatable};
128         $subfield_data{maxlength}  = $subfieldlib->{maxlength};
129         $subfield_data{display_order} = $subfieldlib->{display_order};
130         $subfield_data{kohafield}  = $subfieldlib->{kohafield} || 'items.more_subfields_xml';
131         
132         if ( ! defined( $value ) || $value eq '')  {
133             $value = $subfieldlib->{defaultvalue};
134             if ( $value ) {
135                 # get today date & replace <<YYYY>>, <<YY>>, <<MM>>, <<DD>> if provided in the default value
136                 my $today_dt = dt_from_string;
137                 my $year = $today_dt->strftime('%Y');
138                 my $shortyear = $today_dt->strftime('%y');
139                 my $month = $today_dt->strftime('%m');
140                 my $day = $today_dt->strftime('%d');
141                 $value =~ s/<<YYYY>>/$year/g;
142                 $value =~ s/<<YY>>/$shortyear/g;
143                 $value =~ s/<<MM>>/$month/g;
144                 $value =~ s/<<DD>>/$day/g;
145                 # And <<USER>> with surname (?)
146                 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
147                 $value=~s/<<USER>>/$username/g;
148             }
149         }
150
151         $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
152
153         my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
154         if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
155             foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
156                 my $CNtag       = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
157                 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
158                 $CNsubfields = undef if $CNsubfields eq '';
159                 my $temp2 = $temp->field($CNtag);
160
161                 next unless $temp2;
162                 $value = $temp2->as_string( $CNsubfields, ' ' );
163                 last if $value;
164             }
165         }
166
167         my $default_location = C4::Context->preference('NewItemsDefaultLocation');
168         if ( !$value && $subfieldlib->{kohafield} eq 'items.location' && $default_location ) {
169             $value = $default_location;
170         }
171
172         if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
173             my $input = CGI->new;
174             $value = $input->param('barcode');
175         }
176
177         if ( $subfieldlib->{authorised_value} ) {
178             my @authorised_values;
179             my %authorised_lib;
180             # builds list, depending on authorised value...
181             if ( $subfieldlib->{authorised_value} eq "LOST" ) {
182                 my $ClaimReturnedLostValue = C4::Context->preference('ClaimReturnedLostValue');
183                 my $item_is_return_claim = $ClaimReturnedLostValue && $item && $item->itemlost && $ClaimReturnedLostValue eq $item->itemlost;
184                 $subfield_data{IS_RETURN_CLAIM} = $item_is_return_claim;
185
186                 $subfield_data{IS_LOST_AV} = 1;
187
188                 push @authorised_values, qq{};
189                 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
190                 for my $r ( @$av ) {
191                     push @authorised_values, $r->{authorised_value};
192                     $authorised_lib{$r->{authorised_value}} = $r->{lib};
193                 }
194             }
195             elsif ( $subfieldlib->{authorised_value} eq "branches" ) {
196                 foreach my $thisbranch (@$branches) {
197                     push @authorised_values, $thisbranch->{branchcode};
198                     $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
199                     $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
200                 }
201             }
202             elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
203                   push @authorised_values, "";
204                   my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
205                   my $itemtypes;
206                   if($branch_limit) {
207                       $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
208                   } else {
209                       $itemtypes = Koha::ItemTypes->search_with_localization;
210                   }
211                   while ( my $itemtype = $itemtypes->next ) {
212                       push @authorised_values, $itemtype->itemtype;
213                       $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
214                   }
215
216                   unless ( $value ) {
217                       my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
218                       $itype_sth->execute( $biblionumber );
219                       ( $value ) = $itype_sth->fetchrow_array;
220                   }
221           
222                   #---- class_sources
223             }
224             elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
225                   push @authorised_values, "";
226                     
227                   my $class_sources = GetClassSources();
228                   my $default_source = C4::Context->preference("DefaultClassificationSource");
229                   
230                   foreach my $class_source (sort keys %$class_sources) {
231                       next unless $class_sources->{$class_source}->{'used'} or
232                                   ($value and $class_source eq $value)      or
233                                   ($class_source eq $default_source);
234                       push @authorised_values, $class_source;
235                       $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
236                   }
237                           $value = $default_source unless ($value);
238         
239                   #---- "true" authorised value
240             }
241             else {
242                   push @authorised_values, qq{};
243                   my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
244                   for my $r ( @$av ) {
245                       push @authorised_values, $r->{authorised_value};
246                       $authorised_lib{$r->{authorised_value}} = $r->{lib};
247                   }
248             }
249
250             if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
251                 $subfield_data{marc_value} = {
252                     type        => 'hidden',
253                     id          => $subfield_data{id},
254                     maxlength   => $subfield_data{maxlength},
255                     value       => $value,
256                     ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
257                 };
258             }
259             else {
260                 $subfield_data{marc_value} = {
261                     type     => 'select',
262                     id       => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
263                     values   => \@authorised_values,
264                     labels   => \%authorised_lib,
265                     default  => $value,
266                     ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
267                 };
268             }
269         }
270             # it's a thesaurus / authority field
271         elsif ( $subfieldlib->{authtypecode} ) {
272                 $subfield_data{marc_value} = {
273                     type         => 'text_auth',
274                     id           => $subfield_data{id},
275                     maxlength    => $subfield_data{maxlength},
276                     value        => $value,
277                     authtypecode => $subfieldlib->{authtypecode},
278                 };
279         }
280             # it's a plugin field
281         elsif ( $subfieldlib->{value_builder} ) { # plugin
282             require Koha::FrameworkPlugin;
283             my $plugin = Koha::FrameworkPlugin->new({
284                 name => $subfieldlib->{'value_builder'},
285                 item_style => 1,
286             });
287             my $pars=  { dbh => $dbh, record => $temp, tagslib =>$tagslib,
288                 id => $subfield_data{id}, tabloop => $loop_data };
289             $plugin->build( $pars );
290             if( !$plugin->errstr ) {
291                 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
292                 $subfield_data{marc_value} = {
293                     type        => 'text_plugin',
294                     id          => $subfield_data{id},
295                     maxlength   => $subfield_data{maxlength},
296                     value       => $value,
297                     class       => $class,
298                     nopopup     => $plugin->noclick,
299                     javascript  => $plugin->javascript,
300                 };
301             } else {
302                 warn $plugin->errstr;
303                 $subfield_data{marc_value} = {
304                     type        => 'text',
305                     id          => $subfield_data{id},
306                     maxlength   => $subfield_data{maxlength},
307                     value       => $value,
308                 }; # supply default input form
309             }
310         }
311         elsif ( $tag eq '' ) {       # it's an hidden field
312             $subfield_data{marc_value} = {
313                 type        => 'hidden',
314                 id          => $subfield_data{id},
315                 maxlength   => $subfield_data{maxlength},
316                 value       => $value,
317             };
318         }
319         elsif ( $subfieldlib->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
320             $subfield_data{marc_value} = {
321                 type        => 'text',
322                 id          => $subfield_data{id},
323                 maxlength   => $subfield_data{maxlength},
324                 value       => $value,
325             };
326         }
327         elsif (
328                 (
329                     $value and length($value) > 100
330                 )
331                 or (
332                     C4::Context->preference("marcflavour") eq "UNIMARC"
333                     and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
334                 )
335                 or (
336                     C4::Context->preference("marcflavour") eq "MARC21"
337                     and 500 <= $tag && $tag < 600
338                 )
339               ) {
340             # oversize field (textarea)
341             $subfield_data{marc_value} = {
342                 type        => 'textarea',
343                 id          => $subfield_data{id},
344                 value       => $value,
345             };
346         } else {
347             # it's a standard field
348             $subfield_data{marc_value} = {
349                 type        => 'text',
350                 id          => $subfield_data{id},
351                 maxlength   => $subfield_data{maxlength},
352                 value       => $value,
353             };
354         }
355
356         # Getting list of subfields to keep when restricted editing is enabled
357         my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
358         my $allowAllSubfields = (
359             not defined $subfieldsToAllowForRestrictedEditing
360               or $subfieldsToAllowForRestrictedEditing eq q||
361         ) ? 1 : 0;
362         my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
363
364         # If we're on restricted editing, and our field is not in the list of subfields to allow,
365         # then it is read-only
366         $subfield_data{marc_value}->{readonly} = (
367             not $allowAllSubfields
368             and $restrictededition
369             and !grep { $tag . '$' . $subfieldtag  eq $_ } @subfieldsToAllow
370         ) ? 1: 0;
371
372         return \%subfield_data;
373 }
374
375 # Removes some subfields when prefilling items
376 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
377 sub removeFieldsForPrefill {
378
379     my $item = shift;
380
381     # Getting item tag
382     my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
383
384     # Getting list of subfields to keep
385     my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
386
387     # Removing subfields that are not in the syspref
388     if ($tag && $subfieldsToUseWhenPrefill) {
389         my $field = $item->field($tag);
390         my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
391         foreach my $subfield ($field->subfields()) {
392             if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
393                 $field->delete_subfield(code => $subfield->[0]);
394             }
395
396         }
397     }
398
399     return $item;
400
401 }
402
403 my $input        = CGI->new;
404 my $error        = $input->param('error');
405
406 my $biblionumber;
407 my $itemnumber;
408 if( $input->param('itemnumber') && !$input->param('biblionumber') ){
409     $itemnumber = $input->param('itemnumber');
410     my $item = Koha::Items->find( $itemnumber );
411     $biblionumber = $item->biblionumber;
412 } else {
413     $biblionumber = $input->param('biblionumber');
414     $itemnumber = $input->param('itemnumber');
415 }
416
417 my $op           = $input->param('op') || q{};
418 my $hostitemnumber = $input->param('hostitemnumber');
419 my $marcflavour  = C4::Context->preference("marcflavour");
420 my $searchid     = $input->param('searchid');
421 # fast cataloguing datas
422 my $fa_circborrowernumber = $input->param('circborrowernumber');
423 my $fa_barcode            = $input->param('barcode');
424 my $fa_branch             = $input->param('branch');
425 my $fa_stickyduedate      = $input->param('stickyduedate');
426 my $fa_duedatespec        = $input->param('duedatespec');
427
428 my $frameworkcode = &GetFrameworkCode($biblionumber);
429
430 # Defining which userflag is needing according to the framework currently used
431 my $userflags;
432 if (defined $input->param('frameworkcode')) {
433     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
434 }
435
436 if (not defined $userflags) {
437     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
438 }
439
440 my ($template, $loggedinuser, $cookie)
441     = get_template_and_user({template_name => "cataloguing/additem.tt",
442                  query => $input,
443                  type => "intranet",
444                  flagsrequired => {editcatalogue => $userflags},
445                  });
446
447
448 # Does the user have a restricted item editing permission?
449 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
450 my $restrictededition = $uid ? haspermission($uid,  {'editcatalogue' => 'edit_items_restricted'}) : undef;
451 # In case user is a superlibrarian, editing is not restricted
452 $restrictededition = 0 if ($restrictededition != 0 &&  C4::Context->IsSuperLibrarian());
453 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
454 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
455
456 my $tagslib = &GetMarcStructure(1,$frameworkcode);
457 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
458
459 output_and_exit_if_error( $input, $cookie, $template,
460     { module => 'cataloguing', record => $record } );
461
462 my $oldrecord = TransformMarcToKoha($record);
463 my $itemrecord;
464 my $nextop="additem";
465 my @errors; # store errors found while checking data BEFORE saving item.
466
467 # Getting last created item cookie
468 my $prefillitem = C4::Context->preference('PrefillItem');
469 my $justaddeditem;
470 my $cookieitemrecord;
471 if ($prefillitem) {
472     my $lastitemcookie = $input->cookie('LastCreatedItem');
473     if ($lastitemcookie) {
474         $lastitemcookie = decode_base64url($lastitemcookie);
475         eval {
476             if ( thaw($lastitemcookie) ) {
477                 $cookieitemrecord = thaw($lastitemcookie);
478                 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
479             }
480         };
481         if ($@) {
482             $lastitemcookie = 'undef' unless $lastitemcookie;
483             warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '".encode_base64url($lastitemcookie)."'. Caught error follows: '$@'";
484         }
485     }
486 }
487
488 #-------------------------------------------------------------------------------
489 if ($op eq "additem") {
490
491     #-------------------------------------------------------------------------------
492     # rebuild
493     my @tags      = $input->multi_param('tag');
494     my @subfields = $input->multi_param('subfield');
495     my @values    = $input->multi_param('field_value');
496     # build indicator hash.
497     my @ind_tag   = $input->multi_param('ind_tag');
498     my @indicator = $input->multi_param('indicator');
499     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
500     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
501
502     # type of add
503     my $add_submit                 = $input->param('add_submit');
504     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
505     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
506     my $number_of_copies           = $input->param('number_of_copies');
507
508     # This is a bit tricky : if there is a cookie for the last created item and
509     # we just added an item, the cookie value is not correct yet (it will be updated
510     # next page). To prevent the form from being filled with outdated values, we
511     # force the use of "add and duplicate" feature, so the form will be filled with
512     # correct values.
513     $add_duplicate_submit = 1 if ($prefillitem);
514     $justaddeditem = 1;
515
516     # if autoBarcode is set to 'incremental', calculate barcode...
517     if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
518         $record = _increment_barcode($record, $frameworkcode);
519     }
520
521     my $addedolditem = TransformMarcToKoha( $record );
522
523     # If we have to add or add & duplicate, we add the item
524     if ( $add_submit || $add_duplicate_submit ) {
525
526         # check for item barcode # being unique
527         my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
528         push @errors, "barcode_not_unique" if ($exist_itemnumber);
529
530         # if barcode exists, don't create, but report The problem.
531         unless ($exist_itemnumber) {
532             my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
533
534             # Pushing the last created item cookie back
535             if ($prefillitem && defined $record) {
536                 my $itemcookie = $input->cookie(
537                     -name => 'LastCreatedItem',
538                     # We encode_base64url the whole freezed structure so we're sure we won't have any encoding problems
539                     -value   => encode_base64url( freeze( $record ) ),
540                     -HttpOnly => 1,
541                     -expires => ''
542                 );
543
544                 $cookie = [ $cookie, $itemcookie ];
545             }
546
547         }
548         $nextop = "additem";
549         if ($exist_itemnumber) {
550             $itemrecord = $record;
551         }
552     }
553
554     # If we have to add & duplicate
555     if ($add_duplicate_submit) {
556         $itemrecord = $record;
557         if (C4::Context->preference('autoBarcode') eq 'incremental') {
558             $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
559         }
560         else {
561             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
562             my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
563             my $fieldItem = $itemrecord->field($tagfield);
564             $itemrecord->delete_field($fieldItem);
565             $fieldItem->delete_subfields($tagsubfield);
566             $itemrecord->insert_fields_ordered($fieldItem);
567         }
568     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
569     }
570
571     # If we have to add multiple copies
572     if ($add_multiple_copies_submit) {
573
574         use C4::Barcodes;
575         my $barcodeobj = C4::Barcodes->new;
576         my $copynumber = $addedolditem->{'copynumber'};
577         my $oldbarcode = $addedolditem->{'barcode'};
578         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
579         my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
580
581     # If there is a barcode and we can't find their new values, we can't add multiple copies
582         my $testbarcode;
583         $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
584         if ($oldbarcode && !$testbarcode) {
585
586             push @errors, "no_next_barcode";
587             $itemrecord = $record;
588
589         } else {
590         # We add each item
591
592             # For the first iteration
593             my $barcodevalue = $oldbarcode;
594             my $exist_itemnumber;
595
596
597             for (my $i = 0; $i < $number_of_copies;) {
598
599                 # If there is a barcode
600                 if ($barcodevalue) {
601
602                     # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
603                     $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
604
605                     # Putting it into the record
606                     if ($barcodevalue) {
607                 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
608                     # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
609                     # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
610                     # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
611                     # But when adding multiple copies we need to prefix it here,
612                     # so we retrieve the homebranch from the item and prefix the barcode with it.
613                     my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
614                     my $homebranch = $record->subfield($hb_field, $hb_subfield);
615                     $barcodevalue = $homebranch . $barcodevalue;
616                 }
617                 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
618                     }
619
620                     # Checking if the barcode already exists
621                     $exist_itemnumber = get_item_from_barcode($barcodevalue);
622                 }
623         # Updating record with the new copynumber
624         if ( $copynumber  ){
625             $record->field($copytagfield)->update($copytagsubfield => $copynumber);
626         }
627
628                 # Adding the item
629         if (!$exist_itemnumber) {
630             my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
631                 AddItemFromMarc( $record, $biblionumber, { skip_record_index => 1 } );
632
633             # We count the item only if it was really added
634             # That way, all items are added, even if there was some already existing barcodes
635             # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
636             $i++;
637             # Only increment copynumber if item was really added
638             $copynumber++  if ( $copynumber && $copynumber =~ m/^\d+$/ );
639         }
640
641                 # Preparing the next iteration
642                 $oldbarcode = $barcodevalue;
643             }
644
645         my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
646         $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
647
648             undef($itemrecord);
649         }
650     }   
651     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
652         print $input->redirect(
653            '/cgi-bin/koha/circ/circulation.pl?'
654            .'borrowernumber='.$fa_circborrowernumber
655            .'&barcode='.uri_escape_utf8($fa_barcode)
656            .'&duedatespec='.$fa_duedatespec
657            .'&stickyduedate='.$fa_stickyduedate
658         );
659         exit;
660     }
661
662
663 #-------------------------------------------------------------------------------
664 } elsif ($op eq "edititem") {
665 #-------------------------------------------------------------------------------
666 # retrieve item if exist => then, it's a modif
667     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
668     $nextop = "saveitem";
669 #-------------------------------------------------------------------------------
670 } elsif ($op eq "dupeitem") {
671 #-------------------------------------------------------------------------------
672 # retrieve item if exist => then, it's a modif
673     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
674     if (C4::Context->preference('autoBarcode') eq 'incremental') {
675         $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
676     }
677     else {
678         # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
679         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
680         my $fieldItem = $itemrecord->field($tagfield);
681         $itemrecord->delete_field($fieldItem);
682         $fieldItem->delete_subfields($tagsubfield);
683         $itemrecord->insert_fields_ordered($fieldItem);
684     }
685
686     #check for hidden subfield and remove them for the duplicated item
687     foreach my $field ($itemrecord->fields()){
688         my $tag = $field->{_tag};
689         foreach my $subfield ($field->subfields()){
690             my $subfieldtag = $subfield->[0];
691             if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
692             ||  abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
693                 my $fieldItem = $itemrecord->field($tag);
694                 $itemrecord->delete_field($fieldItem);
695                 $fieldItem->delete_subfields($subfieldtag);
696                 $itemrecord->insert_fields_ordered($fieldItem);
697             }
698         }
699     }
700
701     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
702     $nextop = "additem";
703 #-------------------------------------------------------------------------------
704 } elsif ($op eq "delitem") {
705 #-------------------------------------------------------------------------------
706     # check that there is no issue on this item before deletion.
707     my $item = Koha::Items->find($itemnumber);
708     $error = $item->safe_delete;
709     if(ref($error) eq 'Koha::Item'){
710         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
711     }else{
712         push @errors,$error;
713         $nextop="additem";
714     }
715 #-------------------------------------------------------------------------------
716 } elsif ($op eq "delallitems") {
717 #-------------------------------------------------------------------------------
718     my $items = Koha::Items->search({ biblionumber => $biblionumber });
719     while ( my $item = $items->next ) {
720         $error = $item->safe_delete({ skip_record_index => 1 });
721         next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
722         push @errors,$error;
723     }
724     my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
725     $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
726     if ( @errors ) {
727         $nextop="additem";
728     } else {
729         my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
730         my $views = { C4::Search::enabled_staff_search_views };
731         if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
732             print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
733         } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
734             print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
735         } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
736             print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
737         } else {
738             print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
739         }
740         exit;
741     }
742 #-------------------------------------------------------------------------------
743 } elsif ($op eq "saveitem") {
744 #-------------------------------------------------------------------------------
745
746     my $itemnumber = $input->param('itemnumber');
747     my $item = Koha::Items->find($itemnumber);
748     # FIXME Handle non existent item
749     my $olditemlost = $item->itemlost;
750     my @columns = Koha::Items->columns;
751     for my $c ( @columns ) {
752         if ( $c eq 'more_subfields_xml' ) {
753             my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
754             my @unlinked_item_subfields;
755             for my $subfield ( @more_subfields_xml ) {
756                 my $v = $input->param('items.more_subfields_xml_' . $subfield);
757                 push @unlinked_item_subfields, $subfield, $v;
758             }
759             if ( @unlinked_item_subfields ) {
760                 my $marc = MARC::Record->new();
761                 # use of tag 999 is arbitrary, and doesn't need to match the item tag
762                 # used in the framework
763                 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
764                 $marc->encoding("UTF-8");
765                 $item->more_subfields_xml($marc->as_xml("USMARC"));
766                 next;
767             }
768             $item->more_subfields_xml(undef);
769         } else {
770             my $v = $input->param("items.".$c);
771             next unless defined $v;
772             $item->$c($v);
773         }
774     }
775
776     # check that the barcode don't exist already
777     if ( Koha::Items->search({ barcode => $item->barcode, itemnumber => { '!=' => $item->itemnumber } })->count ) {
778         # FIXME We shouldn't need that, ->store would explode as there is a unique constraint on items.barcode
779         push @errors,"barcode_not_unique";
780     } else {
781         my $newitemlost = $item->itemlost;
782         if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
783             LostItem( $item->itemnumber, 'additem' );
784         }
785         $item->store;
786     }
787
788     $nextop="additem";
789 } elsif ($op eq "delinkitem"){
790
791     my $analyticfield = '773';
792         if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC'){
793         $analyticfield = '773';
794     } elsif ($marcflavour eq 'UNIMARC') {
795         $analyticfield = '461';
796     }
797     foreach my $field ($record->field($analyticfield)){
798         if ($field->subfield('9') eq $hostitemnumber){
799             $record->delete_field($field);
800             last;
801         }
802     }
803         my $modbibresult = ModBiblio($record, $biblionumber,'');
804 }
805
806 # update OAI-PMH sets
807 if ($op) {
808     if (C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
809         C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
810     }
811 }
812
813 #
814 #-------------------------------------------------------------------------------
815 # build screen with existing items. and "new" one
816 #-------------------------------------------------------------------------------
817
818 # now, build existiing item list
819 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
820 #my @fields = $record->fields();
821
822
823 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
824 my @big_array;
825 #---- finds where items.itemnumber is stored
826 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
827 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
828 C4::Biblio::EmbedItemsInMarcBiblio({
829     marc_record  => $temp,
830     biblionumber => $biblionumber });
831 my @fields = $temp->fields();
832
833
834 my @hostitemnumbers;
835 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
836     my $analyticfield = '773';
837     if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC') {
838         $analyticfield = '773';
839     } elsif ($marcflavour eq 'UNIMARC') {
840         $analyticfield = '461';
841     }
842     foreach my $hostfield ($temp->field($analyticfield)){
843         my $hostbiblionumber = $hostfield->subfield('0');
844         if ($hostbiblionumber){
845             my $hostrecord = GetMarcBiblio({
846                 biblionumber => $hostbiblionumber,
847                 embed_items  => 1 });
848             if ($hostrecord) {
849                 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
850                 foreach my $hostitem ($hostrecord->field($itemfield)){
851                     if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
852                         push (@fields, $hostitem);
853                         push (@hostitemnumbers, $hostfield->subfield('9'));
854                     }
855                 }
856             }
857         }
858     }
859 }
860
861 foreach my $field (@fields) {
862     next if ( $field->tag() < 10 );
863
864     my @subf = $field->subfields or ();    # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
865     my %this_row;
866     # loop through each subfield
867     my $i = 0;
868     foreach my $subfield (@subf){
869         my $subfieldcode = $subfield->[0];
870         my $subfieldvalue= $subfield->[1];
871
872         next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10 
873                 && ($field->tag() ne $itemtagfield 
874                 && $subfieldcode   ne $itemtagsubfield));
875         $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10);
876                 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10) {
877                     $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
878                 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
879                         $subfieldcode, $subfieldvalue, '', $tagslib) 
880                                                 || $subfieldvalue;
881         }
882
883         if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
884             #verifying rights
885             my $userenv = C4::Context->userenv();
886             unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
887                 $this_row{'nomod'} = 1;
888             }
889         }
890         $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
891
892         if ( C4::Context->preference('EasyAnalyticalRecords') ) {
893             foreach my $hostitemnumber (@hostitemnumbers) {
894                 my $item = Koha::Items->find( $hostitemnumber );
895                 if ($this_row{itemnumber} eq $hostitemnumber) {
896                     $this_row{hostitemflag} = 1;
897                     $this_row{hostbiblionumber}= $item->biblio->biblionumber;
898                     last;
899                 }
900             }
901         }
902     }
903     if (%this_row) {
904         push(@big_array, \%this_row);
905     }
906 }
907
908 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
909 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
910
911 # now, construct template !
912 # First, the existing items for display
913 my @item_value_loop;
914 my @header_value_loop;
915 for my $row ( @big_array ) {
916     my %row_data;
917     my @item_fields;
918     foreach my $key (sort keys %witness){
919         my $item_field;
920         if ( $row->{$key} ){
921             $item_field->{field} = $row->{$key};
922         } else {
923             $item_field->{field} = '';
924         }
925
926         for my $kohafield (
927             qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
928           )
929         {
930             my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
931             next unless $key eq $subfield;
932             $item_field->{datatype} = 'date';
933         }
934
935         push @item_fields, $item_field;
936     }
937     $row_data{item_value} = [ @item_fields ];
938     $row_data{itemnumber} = $row->{itemnumber};
939     #reporting this_row values
940     $row_data{'nomod'} = $row->{'nomod'};
941     $row_data{'hostitemflag'} = $row->{'hostitemflag'};
942     $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
943 #       $row_data{'countanalytics'} = $row->{'countanalytics'};
944     push(@item_value_loop,\%row_data);
945 }
946 foreach my $subfield_code (sort keys(%witness)) {
947     my %header_value;
948     $header_value{header_value} = $witness{$subfield_code};
949
950     my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
951     my $kohafield = $subfieldlib->{kohafield};
952     if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
953         $header_value{column_name} = $1;
954     }
955
956     push(@header_value_loop, \%header_value);
957 }
958
959 # now, build the item form for entering a new item
960 my @loop_data =();
961 my $i=0;
962
963 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
964 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
965 for my $library ( @$libraries ) {
966     $library->{selected} = 1 if $library->{branchcode} eq $branch
967 }
968
969 my $item = Koha::Items->find($itemnumber);
970
971 # We generate form, from actuel record
972 @fields = ();
973 if($itemrecord){
974     foreach my $field ($itemrecord->fields()){
975         my $tag = $field->{_tag};
976         foreach my $subfield ( $field->subfields() ){
977
978             my $subfieldtag = $subfield->[0];
979             my $value       = $subfield->[1];
980             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
981
982             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
983
984             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
985             push @fields, "$tag$subfieldtag";
986             push (@loop_data, $subfield_data);
987             $i++;
988                     }
989
990                 }
991             }
992     # and now we add fields that are empty
993
994 # Using last created item if it exists
995
996 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
997
998 # We generate form, and fill with values if defined
999 foreach my $tag ( keys %{$tagslib}){
1000     foreach my $subtag (keys %{$tagslib->{$tag}}){
1001         next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
1002         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
1003         next if any { /^$tag$subtag$/ }  @fields;
1004
1005         my @values = (undef);
1006         @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
1007         for my $value (@values){
1008             my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
1009             push (@loop_data, $subfield_data);
1010             $i++;
1011         }
1012   }
1013 }
1014 @loop_data = sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} } @loop_data;
1015
1016 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
1017 $template->param(
1018     biblionumber => $biblionumber,
1019     title        => $oldrecord->{title},
1020     author       => $oldrecord->{author},
1021     item_loop        => \@item_value_loop,
1022     item_header_loop => \@header_value_loop,
1023     item             => \@loop_data,
1024     itemnumber       => $itemnumber,
1025     barcode          => $item ? $item->barcode : undef,
1026     itemtagfield     => $itemtagfield,
1027     itemtagsubfield  => $itemtagsubfield,
1028     op      => $nextop,
1029     popup => scalar $input->param('popup') ? 1: 0,
1030     C4::Search::enabled_staff_search_views,
1031 );
1032 $template->{'VARS'}->{'searchid'} = $searchid;
1033
1034 if ($frameworkcode eq 'FA'){
1035     # fast cataloguing datas
1036     $template->param(
1037         'circborrowernumber' => $fa_circborrowernumber,
1038         'barcode'            => $fa_barcode,
1039         'branch'             => $fa_branch,
1040         'stickyduedate'      => $fa_stickyduedate,
1041         'duedatespec'        => $fa_duedatespec,
1042     );
1043 }
1044
1045 foreach my $error (@errors) {
1046     $template->param($error => 1);
1047 }
1048 output_html_with_http_headers $input, $cookie, $template->output;