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