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