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