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