Bug 27526: Fix repeatable more subfields
[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
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 C4::Barcodes;
44 use C4::Barcodes::ValueBuilder;
45 use Koha::DateUtils qw( dt_from_string );
46 use Koha::Items;
47 use Koha::ItemTypes;
48 use Koha::Libraries;
49 use Koha::Patrons;
50 use Koha::SearchEngine::Indexer;
51 use C4::Search qw( enabled_staff_search_views );
52 use Storable qw( freeze thaw );
53 use URI::Escape qw( uri_escape_utf8 );
54 use C4::Members;
55
56 use MARC::File::XML;
57 use URI::Escape qw( uri_escape_utf8 );
58 use MIME::Base64 qw( decode_base64url encode_base64url );
59 use List::Util qw( first );
60 use List::MoreUtils qw( any uniq );
61
62 our $dbh = C4::Context->dbh;
63
64 sub generate_subfield_form {
65         my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $subfields, $i, $restrictededition, $item) = @_;
66   
67         my $frameworkcode = &GetFrameworkCode($biblionumber);
68
69         $item //= {};
70
71         my %subfield_data;
72         my $dbh = C4::Context->dbh;
73         
74         my $index_subfield = int(rand(1000000)); 
75         if ($subfieldtag eq '@'){
76             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
77         } else {
78             $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
79         }
80         
81         $subfield_data{tag}        = $tag;
82         $subfield_data{subfield}   = $subfieldtag;
83         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
84         $subfield_data{mandatory}  = $subfieldlib->{mandatory};
85         $subfield_data{important}  = $subfieldlib->{important};
86         $subfield_data{repeatable} = $subfieldlib->{repeatable};
87         $subfield_data{maxlength}  = $subfieldlib->{maxlength};
88         $subfield_data{display_order} = $subfieldlib->{display_order};
89         $subfield_data{kohafield}  = $subfieldlib->{kohafield} || 'items.more_subfields_xml';
90         
91         if ( ! defined( $value ) || $value eq '')  {
92             $value = $subfieldlib->{defaultvalue};
93             if ( $value ) {
94                 # get today date & replace <<YYYY>>, <<YY>>, <<MM>>, <<DD>> if provided in the default value
95                 my $today_dt = dt_from_string;
96                 my $year = $today_dt->strftime('%Y');
97                 my $shortyear = $today_dt->strftime('%y');
98                 my $month = $today_dt->strftime('%m');
99                 my $day = $today_dt->strftime('%d');
100                 $value =~ s/<<YYYY>>/$year/g;
101                 $value =~ s/<<YY>>/$shortyear/g;
102                 $value =~ s/<<MM>>/$month/g;
103                 $value =~ s/<<DD>>/$day/g;
104                 # And <<USER>> with surname (?)
105                 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
106                 $value=~s/<<USER>>/$username/g;
107             }
108         }
109
110         $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
111
112         my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
113         if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
114             foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
115                 my $CNtag       = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
116                 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
117                 $CNsubfields = undef if $CNsubfields eq '';
118                 my $temp2 = $temp->field($CNtag);
119
120                 next unless $temp2;
121                 $value = $temp2->as_string( $CNsubfields, ' ' );
122                 last if $value;
123             }
124         }
125
126         my $default_location = C4::Context->preference('NewItemsDefaultLocation');
127         if ( !$value && $subfieldlib->{kohafield} eq 'items.location' && $default_location ) {
128             $value = $default_location;
129         }
130
131         if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
132             my $input = CGI->new;
133             $value = $input->param('barcode');
134         }
135
136         if ( $subfieldlib->{authorised_value} ) {
137             my @authorised_values;
138             my %authorised_lib;
139             # builds list, depending on authorised value...
140             if ( $subfieldlib->{authorised_value} eq "LOST" ) {
141                 my $ClaimReturnedLostValue = C4::Context->preference('ClaimReturnedLostValue');
142                 my $item_is_return_claim = $ClaimReturnedLostValue && exists $item->{itemlost} && $ClaimReturnedLostValue eq $item->{itemlost};
143                 $subfield_data{IS_RETURN_CLAIM} = $item_is_return_claim;
144
145                 $subfield_data{IS_LOST_AV} = 1;
146
147                 push @authorised_values, qq{};
148                 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
149                 for my $r ( @$av ) {
150                     push @authorised_values, $r->{authorised_value};
151                     $authorised_lib{$r->{authorised_value}} = $r->{lib};
152                 }
153             }
154             elsif ( $subfieldlib->{authorised_value} eq "branches" ) {
155                 foreach my $thisbranch (@$branches) {
156                     push @authorised_values, $thisbranch->{branchcode};
157                     $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
158                     $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
159                 }
160             }
161             elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
162                   push @authorised_values, "";
163                   my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
164                   my $itemtypes;
165                   if($branch_limit) {
166                       $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
167                   } else {
168                       $itemtypes = Koha::ItemTypes->search_with_localization;
169                   }
170                   while ( my $itemtype = $itemtypes->next ) {
171                       push @authorised_values, $itemtype->itemtype;
172                       $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
173                   }
174
175                   unless ( $value ) {
176                       my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
177                       $itype_sth->execute( $biblionumber );
178                       ( $value ) = $itype_sth->fetchrow_array;
179                   }
180           
181                   #---- class_sources
182             }
183             elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
184                   push @authorised_values, "";
185                     
186                   my $class_sources = GetClassSources();
187                   my $default_source = C4::Context->preference("DefaultClassificationSource");
188                   
189                   foreach my $class_source (sort keys %$class_sources) {
190                       next unless $class_sources->{$class_source}->{'used'} or
191                                   ($value and $class_source eq $value)      or
192                                   ($class_source eq $default_source);
193                       push @authorised_values, $class_source;
194                       $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
195                   }
196                           $value = $default_source unless ($value);
197         
198                   #---- "true" authorised value
199             }
200             else {
201                   push @authorised_values, qq{};
202                   my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
203                   for my $r ( @$av ) {
204                       push @authorised_values, $r->{authorised_value};
205                       $authorised_lib{$r->{authorised_value}} = $r->{lib};
206                   }
207             }
208
209             if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
210                 $subfield_data{marc_value} = {
211                     type        => 'hidden',
212                     id          => $subfield_data{id},
213                     maxlength   => $subfield_data{maxlength},
214                     value       => $value,
215                     ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
216                 };
217             }
218             else {
219                 $subfield_data{marc_value} = {
220                     type     => 'select',
221                     id       => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
222                     values   => \@authorised_values,
223                     labels   => \%authorised_lib,
224                     default  => $value,
225                     ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
226                 };
227             }
228         }
229             # it's a thesaurus / authority field
230         elsif ( $subfieldlib->{authtypecode} ) {
231                 $subfield_data{marc_value} = {
232                     type         => 'text_auth',
233                     id           => $subfield_data{id},
234                     maxlength    => $subfield_data{maxlength},
235                     value        => $value,
236                     authtypecode => $subfieldlib->{authtypecode},
237                 };
238         }
239             # it's a plugin field
240         elsif ( $subfieldlib->{value_builder} ) { # plugin
241             require Koha::FrameworkPlugin;
242             my $plugin = Koha::FrameworkPlugin->new({
243                 name => $subfieldlib->{'value_builder'},
244                 item_style => 1,
245             });
246             my $pars=  { dbh => $dbh, record => $temp, tagslib =>$tagslib,
247                 id => $subfield_data{id}, tabloop => $subfields };
248             $plugin->build( $pars );
249             if( !$plugin->errstr ) {
250                 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
251                 $subfield_data{marc_value} = {
252                     type        => 'text_plugin',
253                     id          => $subfield_data{id},
254                     maxlength   => $subfield_data{maxlength},
255                     value       => $value,
256                     class       => $class,
257                     nopopup     => $plugin->noclick,
258                     javascript  => $plugin->javascript,
259                 };
260             } else {
261                 warn $plugin->errstr;
262                 $subfield_data{marc_value} = {
263                     type        => 'text',
264                     id          => $subfield_data{id},
265                     maxlength   => $subfield_data{maxlength},
266                     value       => $value,
267                 }; # supply default input form
268             }
269         }
270         elsif ( $tag eq '' ) {       # it's an hidden field
271             $subfield_data{marc_value} = {
272                 type        => 'hidden',
273                 id          => $subfield_data{id},
274                 maxlength   => $subfield_data{maxlength},
275                 value       => $value,
276             };
277         }
278         elsif ( $subfieldlib->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
279             $subfield_data{marc_value} = {
280                 type        => 'text',
281                 id          => $subfield_data{id},
282                 maxlength   => $subfield_data{maxlength},
283                 value       => $value,
284             };
285         }
286         elsif (
287                 (
288                     $value and length($value) > 100
289                 )
290                 or (
291                     C4::Context->preference("marcflavour") eq "UNIMARC"
292                     and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
293                 )
294                 or (
295                     C4::Context->preference("marcflavour") eq "MARC21"
296                     and 500 <= $tag && $tag < 600
297                 )
298               ) {
299             # oversize field (textarea)
300             $subfield_data{marc_value} = {
301                 type        => 'textarea',
302                 id          => $subfield_data{id},
303                 value       => $value,
304             };
305         } else {
306             # it's a standard field
307             $subfield_data{marc_value} = {
308                 type        => 'text',
309                 id          => $subfield_data{id},
310                 maxlength   => $subfield_data{maxlength},
311                 value       => $value,
312             };
313         }
314
315         # Getting list of subfields to keep when restricted editing is enabled
316         my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
317         my $allowAllSubfields = (
318             not defined $subfieldsToAllowForRestrictedEditing
319               or $subfieldsToAllowForRestrictedEditing eq q||
320         ) ? 1 : 0;
321         my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
322
323         # If we're on restricted editing, and our field is not in the list of subfields to allow,
324         # then it is read-only
325         $subfield_data{marc_value}->{readonly} = (
326             not $allowAllSubfields
327             and $restrictededition
328             and !grep { $tag . '$' . $subfieldtag  eq $_ } @subfieldsToAllow
329         ) ? 1: 0;
330
331         return \%subfield_data;
332 }
333
334 my $input        = CGI->new;
335 my $error        = $input->param('error');
336
337 my $biblionumber;
338 my $itemnumber;
339 if( $input->param('itemnumber') && !$input->param('biblionumber') ){
340     $itemnumber = $input->param('itemnumber');
341     my $item = Koha::Items->find( $itemnumber );
342     $biblionumber = $item->biblionumber;
343 } else {
344     $biblionumber = $input->param('biblionumber');
345     $itemnumber = $input->param('itemnumber');
346 }
347
348 my $biblio = Koha::Biblios->find($biblionumber);
349
350 my $op           = $input->param('op') || q{};
351 my $hostitemnumber = $input->param('hostitemnumber');
352 my $marcflavour  = C4::Context->preference("marcflavour");
353 my $searchid     = $input->param('searchid');
354 # fast cataloguing datas
355 my $fa_circborrowernumber = $input->param('circborrowernumber');
356 my $fa_barcode            = $input->param('barcode');
357 my $fa_branch             = $input->param('branch');
358 my $fa_stickyduedate      = $input->param('stickyduedate');
359 my $fa_duedatespec        = $input->param('duedatespec');
360
361 our $frameworkcode = &GetFrameworkCode($biblionumber);
362
363 # Defining which userflag is needing according to the framework currently used
364 my $userflags;
365 if (defined $input->param('frameworkcode')) {
366     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
367 }
368
369 if (not defined $userflags) {
370     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
371 }
372
373 my ($template, $loggedinuser, $cookie)
374     = get_template_and_user({template_name => "cataloguing/additem.tt",
375                  query => $input,
376                  type => "intranet",
377                  flagsrequired => {editcatalogue => $userflags},
378                  });
379
380
381 # Does the user have a restricted item editing permission?
382 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
383 my $restrictededition = $uid ? haspermission($uid,  {'editcatalogue' => 'edit_items_restricted'}) : undef;
384 # In case user is a superlibrarian, editing is not restricted
385 $restrictededition = 0 if ($restrictededition != 0 &&  C4::Context->IsSuperLibrarian());
386 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
387 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
388
389 our $tagslib = &GetMarcStructure(1,$frameworkcode);
390 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
391
392 output_and_exit_if_error( $input, $cookie, $template,
393     { module => 'cataloguing', record => $record } );
394
395 my $oldrecord = TransformMarcToKoha($record);
396 my $current_item;
397 my $nextop="additem";
398 my @errors; # store errors found while checking data BEFORE saving item.
399
400 # Getting last created item cookie
401 my $prefillitem = C4::Context->preference('PrefillItem');
402 my $item_from_cookie;
403 if ($prefillitem) {
404     my $lastitemcookie = $input->cookie('LastCreatedItem');
405     if ($lastitemcookie) {
406         $lastitemcookie = decode_base64url($lastitemcookie);
407         eval {
408             if ( thaw($lastitemcookie) ) {
409                 $item_from_cookie = thaw($lastitemcookie);
410             }
411         };
412         if ($@) {
413             $lastitemcookie = 'undef' unless $lastitemcookie;
414             warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '".encode_base64url($lastitemcookie)."'. Caught error follows: '$@'";
415         }
416     }
417 }
418
419 #-------------------------------------------------------------------------------
420 if ($op eq "additem") {
421
422     my $add_submit                 = $input->param('add_submit');
423     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
424     my $number_of_copies           = $input->param('number_of_copies');
425
426     my @columns = Koha::Items->columns;
427     my $item = Koha::Item->new;
428     $item->biblionumber($biblio->biblionumber);
429     for my $c ( @columns ) {
430         if ( $c eq 'more_subfields_xml' ) {
431             my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
432             my @unlinked_item_subfields;
433             for my $subfield ( @more_subfields_xml ) {
434                 my $v = $input->param('items.more_subfields_xml_' . $subfield);
435                 push @unlinked_item_subfields, $subfield, $v;
436             }
437             if ( @unlinked_item_subfields ) {
438                 my $marc = MARC::Record->new();
439                 # use of tag 999 is arbitrary, and doesn't need to match the item tag
440                 # used in the framework
441                 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
442                 $marc->encoding("UTF-8");
443                 $item->more_subfields_xml($marc->as_xml("USMARC"));
444                 next;
445             }
446             $item->more_subfields_xml(undef);
447         } else {
448             my @v = $input->multi_param("items.".$c);
449             next unless @v;
450             $item->$c(join ' | ', uniq @v);
451         }
452     }
453
454     # if autoBarcode is set to 'incremental', calculate barcode...
455     if ( not $item->barcode && C4::Context->preference('autoBarcode') eq 'incremental' ) {
456         my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
457         $item->barcode($barcode);
458     }
459
460     # If we have to add or add & duplicate, we add the item
461     if ( $add_submit || $prefillitem) {
462
463         # check for item barcode # being unique
464         if ( Koha::Items->search({ barcode => $item->barcode })->count ) {
465             # if barcode exists, don't create, but report The problem.
466             push @errors, "barcode_not_unique";
467
468             $current_item = $item->unblessed; # Restore edit form for the same item
469         }
470         else {
471             $item->store->discard_changes;
472
473             # This is a bit tricky : if there is a cookie for the last created item and
474             # we just added an item, the cookie value is not correct yet (it will be updated
475             # next page). To prevent the form from being filled with outdated values, we
476             # force the use of "add and duplicate" feature, so the form will be filled with
477             # correct values.
478
479             # FIXME This need to be rewritten, we must store $item->unblessed instead
480             # Pushing the last created item cookie back
481             if ( $prefillitem ) {
482                 $item_from_cookie = $input->cookie(
483                     -name => 'LastCreatedItem',
484                     # We encode_base64url the whole freezed structure so we're sure we won't have any encoding problems
485                     -value   => encode_base64url( freeze( { %{$item->unblessed}, itemnumber => undef } ) ),
486                     -HttpOnly => 1,
487                     -expires => ''
488                 );
489
490                 $cookie = [ $cookie, $item_from_cookie ];
491             }
492
493         }
494         $nextop = "additem";
495
496     }
497
498     # If we have to add & duplicate
499     if ($prefillitem) {
500         if (C4::Context->preference('autoBarcode') eq 'incremental') {
501             my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
502             $current_item->{barcode} = $barcode;
503         }
504         else {
505             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
506             $current_item->{barcode} = undef; # FIXME or delete?
507         }
508     }
509
510     # If we have to add multiple copies
511     if ($add_multiple_copies_submit) {
512
513         $current_item = $item->unblessed;
514
515         my $copynumber = $current_item->{copynumber};
516         my $oldbarcode = $current_item->{barcode};
517
518         # If there is a barcode and we can't find their new values, we can't add multiple copies
519         my $testbarcode;
520         my $barcodeobj = C4::Barcodes->new;
521         $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
522         if ( $oldbarcode && !$testbarcode ) {
523
524             push @errors, "no_next_barcode";
525
526         }
527         else {
528             # We add each item
529
530             # For the first iteration
531             my $barcodevalue = $oldbarcode;
532             my $exist_itemnumber;
533
534             for ( my $i = 0 ; $i < $number_of_copies ; ) {
535
536                 # If there is a barcode
537                 if ($barcodevalue) {
538
539 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
540                     $barcodevalue = $barcodeobj->next_value($oldbarcode)
541                       if ( $i > 0 || $exist_itemnumber );
542
543                     # Putting it into the record
544                     if ($barcodevalue) {
545                         if ( C4::Context->preference("autoBarcode") eq
546                             'hbyymmincr' && $i > 0 )
547                         { # The first copy already contains the homebranch prefix
548                              # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
549                              # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
550                              # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
551                              # But when adding multiple copies we need to prefix it here,
552                              # so we retrieve the homebranch from the item and prefix the barcode with it.
553                             my $homebranch = $current_item->{homebranch};
554                             $barcodevalue = $homebranch . $barcodevalue;
555                         }
556                         $current_item->{barcode} = $barcodevalue;
557                     }
558
559                     # Checking if the barcode already exists
560                     $exist_itemnumber = Koha::Items->search({ barcode => $barcodevalue })->count;
561                 }
562
563                 # Updating record with the new copynumber
564                 if ($copynumber) {
565                     $current_item->{copynumber} = $copynumber;
566                 }
567
568                 # Adding the item
569                 if ( !$exist_itemnumber ) {
570                     delete $current_item->{itemnumber};
571                     $current_item = Koha::Item->new($current_item)->store(
572                         { skip_record_index => 1 } );
573                     $current_item->discard_changes; # Cannot chain discard_changes
574                     $current_item = $current_item->unblessed;
575                     set_item_default_location($current_item->{itemnumber});
576
577 # We count the item only if it was really added
578 # That way, all items are added, even if there was some already existing barcodes
579 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
580                     $i++;
581
582                     # Only increment copynumber if item was really added
583                     $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
584                 }
585
586                 # Preparing the next iteration
587                 $oldbarcode = $barcodevalue;
588             }
589
590             my $indexer = Koha::SearchEngine::Indexer->new(
591                 { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
592             $indexer->index_records( $biblionumber, "specialUpdate",
593                 "biblioserver" );
594
595             undef($current_item);
596         }
597     }
598     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
599         print $input->redirect(
600            '/cgi-bin/koha/circ/circulation.pl?'
601            .'borrowernumber='.$fa_circborrowernumber
602            .'&barcode='.uri_escape_utf8($fa_barcode)
603            .'&duedatespec='.$fa_duedatespec
604            .'&stickyduedate='.$fa_stickyduedate
605         );
606         exit;
607     }
608
609
610 #-------------------------------------------------------------------------------
611 } elsif ($op eq "edititem") {
612 #-------------------------------------------------------------------------------
613 # retrieve item if exist => then, it's a modif
614     $current_item = Koha::Items->find($itemnumber)->unblessed;
615     # FIXME Handle non existent item
616     $nextop = "saveitem";
617 #-------------------------------------------------------------------------------
618 } elsif ($op eq "dupeitem") {
619 #-------------------------------------------------------------------------------
620 # retrieve item if exist => then, it's a modif
621     my $item = Koha::Items->find($itemnumber);
622     # FIXME Handle non existent item
623     if (C4::Context->preference('autoBarcode') eq 'incremental') {
624         my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
625         $item->barcode($barcode);
626     }
627     else {
628         $item->barcode(undef); # Don't save it!
629     }
630
631     $nextop = "additem";
632 #-------------------------------------------------------------------------------
633 } elsif ($op eq "delitem") {
634 #-------------------------------------------------------------------------------
635     # check that there is no issue on this item before deletion.
636     my $item = Koha::Items->find($itemnumber);
637     $error = $item->safe_delete;
638     if(ref($error) eq 'Koha::Item'){
639         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
640     }else{
641         push @errors,$error;
642         $nextop="additem";
643     }
644 #-------------------------------------------------------------------------------
645 } elsif ($op eq "delallitems") {
646 #-------------------------------------------------------------------------------
647     my $items = Koha::Items->search({ biblionumber => $biblionumber });
648     while ( my $item = $items->next ) {
649         $error = $item->safe_delete({ skip_record_index => 1 });
650         next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
651         push @errors,$error;
652     }
653     my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
654     $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
655     if ( @errors ) {
656         $nextop="additem";
657     } else {
658         my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
659         my $views = { C4::Search::enabled_staff_search_views };
660         if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
661             print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
662         } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
663             print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
664         } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
665             print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
666         } else {
667             print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
668         }
669         exit;
670     }
671 #-------------------------------------------------------------------------------
672 } elsif ($op eq "saveitem") {
673 #-------------------------------------------------------------------------------
674
675     my $itemnumber = $input->param('itemnumber');
676     my $item = Koha::Items->find($itemnumber);
677     # FIXME Handle non existent item
678     my $olditemlost = $item->itemlost;
679     my @columns = Koha::Items->columns;
680     for my $c ( @columns ) {
681         if ( $c eq 'more_subfields_xml' ) {
682             my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
683             my @unlinked_item_subfields;
684             for my $subfield ( uniq @more_subfields_xml ) {
685                 my @v = $input->multi_param('items.more_subfields_xml_' . $subfield);
686                 push @unlinked_item_subfields, $subfield, $_ for @v;
687             }
688             if ( @unlinked_item_subfields ) {
689                 my $marc = MARC::Record->new();
690                 # use of tag 999 is arbitrary, and doesn't need to match the item tag
691                 # used in the framework
692                 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
693                 $marc->encoding("UTF-8");
694                 $item->more_subfields_xml($marc->as_xml("USMARC"));
695                 next;
696             }
697             $item->more_subfields_xml(undef);
698         } else {
699             my @v = $input->multi_param("items.".$c);
700             next unless @v;
701             $item->$c(join ' | ', uniq @v);
702         }
703     }
704
705     # check that the barcode don't exist already
706     if ( Koha::Items->search({ barcode => $item->barcode, itemnumber => { '!=' => $item->itemnumber } })->count ) {
707         # FIXME We shouldn't need that, ->store would explode as there is a unique constraint on items.barcode
708         push @errors,"barcode_not_unique";
709         $current_item = $item->unblessed; # Restore edit form for the same item
710     } else {
711         my $newitemlost = $item->itemlost;
712         if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
713             LostItem( $item->itemnumber, 'additem' );
714         }
715         $item->store;
716     }
717
718     $nextop="additem";
719 } elsif ($op eq "delinkitem"){
720
721     my $analyticfield = '773';
722         if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC'){
723         $analyticfield = '773';
724     } elsif ($marcflavour eq 'UNIMARC') {
725         $analyticfield = '461';
726     }
727     foreach my $field ($record->field($analyticfield)){
728         if ($field->subfield('9') eq $hostitemnumber){
729             $record->delete_field($field);
730             last;
731         }
732     }
733         my $modbibresult = ModBiblio($record, $biblionumber,'');
734 }
735
736 # update OAI-PMH sets
737 if ($op) {
738     if (C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
739         C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
740     }
741 }
742
743 #
744 #-------------------------------------------------------------------------------
745 # build screen with existing items. and "new" one
746 #-------------------------------------------------------------------------------
747
748 # now, build existiing item list
749
750 my @items;
751 for my $item ( $biblio->items->as_list, $biblio->host_items->as_list ) {
752     push @items, $item->columns_to_str;
753 }
754
755 my @witness_attributes = uniq map {
756     my $item = $_;
757     map { defined $item->{$_} && $item->{$_} ne "" ? $_ : () } keys %$item
758 } @items;
759
760 our ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField("items.itemnumber");
761
762 my $subfieldcode_attribute_mappings;
763 for my $subfield_code ( keys %{ $tagslib->{$itemtagfield} } ) {
764
765     my $subfield = $tagslib->{$itemtagfield}->{$subfield_code};
766
767     next if IsMarcStructureInternal( $subfield );
768     next unless $subfield->{tab} eq 10; # Is this really needed?
769
770     my $attribute;
771     if ( $subfield->{kohafield} ) {
772         ( $attribute = $subfield->{kohafield} ) =~ s|^items\.||;
773     } else {
774         $attribute = $subfield_code; # It's in more_subfields_xml
775     }
776     next unless grep { $attribute eq $_ } @witness_attributes;
777     $subfieldcode_attribute_mappings->{$subfield_code} = $attribute;
778 }
779
780 my @header_value_loop = map {
781     {
782         header_value  => $tagslib->{$itemtagfield}->{$_}->{lib},
783         attribute     => $subfieldcode_attribute_mappings->{$_},
784         subfield_code => $_,
785     }
786 } sort keys %$subfieldcode_attribute_mappings;
787
788 # now, build the item form for entering a new item
789 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
790 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
791 for my $library ( @$libraries ) {
792     $library->{selected} = 1 if $library->{branchcode} eq $branch
793 }
794
795
796 # Using last created item if it exists
797 $current_item = $item_from_cookie
798   if $item_from_cookie
799   && $prefillitem
800   && $op ne "additem"
801   && $op ne "edititem";
802
803 my @subfields_to_prefill = split ' ', C4::Context->preference('SubfieldsToUseWhenPrefill');
804
805 if ( $current_item->{more_subfields_xml} ) {
806     $current_item->{marc_more_subfields_xml} = MARC::Record->new_from_xml($current_item->{more_subfields_xml}, 'UTF-8');
807 }
808
809 # We generate form, and fill with values if defined
810 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
811 my $i = 0;
812 my @subfields;
813 foreach my $tag ( keys %{$tagslib} ) {
814     foreach my $subtag ( keys %{ $tagslib->{$tag} } ) {
815
816         my $subfield = $tagslib->{$tag}{$subtag};
817
818         next if IsMarcStructureInternal( $subfield );
819         next if ( $subfield->{tab} ne "10" );
820
821         my @values = ();
822
823         my $subfield_data;
824
825         # If we are not adding a new item
826         # OR
827         # If the subfield must be prefilled with last catalogued item
828         if (
829             $nextop ne 'additem'
830             || (
831                 !$prefillitem
832                 || ( $prefillitem && grep { $_ eq $subtag }
833                     @subfields_to_prefill )
834             )
835           )
836         {
837             my $kohafield = $subfield->{kohafield};
838             if ($kohafield) {
839
840                 # This is a mapped field
841                 ( my $attribute = $kohafield ) =~ s|^items\.||;
842                 push @values, $subfield->{repeatable}
843                     ? split '\s\|\s', $current_item->{$attribute}
844                     : $current_item->{$attribute}
845                   if defined $current_item->{$attribute};
846             } else {
847                 # Not mapped, picked the values from more_subfields_xml's MARC
848                 my $marc_more = $current_item->{marc_more_subfields_xml};
849                 if ( $marc_more ) {
850                     for my $f ( $marc_more->fields($tag) ) {
851                         push @values, $f->subfield($subtag);
852                     }
853                 }
854             }
855         }
856
857         @values = ('') unless @values;
858
859         for my $value (@values) {
860             my $subfield_data = generate_subfield_form(
861                 $tag,                        $subtag,
862                 $value,                      $tagslib,
863                 $subfield,                   $libraries,
864                 $biblionumber,               $temp,
865                 \@subfields,                 $i,
866                 $restrictededition,          $current_item,
867             );
868             push @subfields, $subfield_data;
869             $i++;
870         }
871     }
872 }
873 @subfields = sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} } @subfields;
874
875 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
876 $template->param(
877     biblionumber => $biblionumber,
878     title        => $oldrecord->{title},
879     author       => $oldrecord->{author},
880     items        => \@items,
881     item_header_loop => \@header_value_loop,
882     subfields    => \@subfields,
883     itemnumber       => $itemnumber,
884     barcode          => $current_item->{barcode},
885     itemtagfield     => $itemtagfield,
886     itemtagsubfield  => $itemtagsubfield,
887     op      => $nextop,
888     popup => scalar $input->param('popup') ? 1: 0,
889     C4::Search::enabled_staff_search_views,
890 );
891 $template->{'VARS'}->{'searchid'} = $searchid;
892
893 if ($frameworkcode eq 'FA'){
894     # fast cataloguing datas
895     $template->param(
896         'circborrowernumber' => $fa_circborrowernumber,
897         'barcode'            => $fa_barcode,
898         'branch'             => $fa_branch,
899         'stickyduedate'      => $fa_stickyduedate,
900         'duedatespec'        => $fa_duedatespec,
901     );
902 }
903
904 foreach my $error (@errors) {
905     $template->param($error => 1);
906 }
907 output_html_with_http_headers $input, $cookie, $template->output;