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