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