Bug 23463: Replace ModItem with Koha::Item->store
[koha-equinox.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 List::MoreUtils qw/any/;
39 use C4::Search;
40 use Storable qw(thaw freeze);
41 use URI::Escape;
42 use C4::Members;
43
44 use MARC::File::XML;
45 use URI::Escape;
46
47 our $dbh = C4::Context->dbh;
48
49 sub find_value {
50     my ($tagfield,$insubfield,$record) = @_;
51     my $result;
52     my $indicator;
53     foreach my $field ($record->field($tagfield)) {
54         my @subfields = $field->subfields();
55         foreach my $subfield (@subfields) {
56             if (@$subfield[0] eq $insubfield) {
57                 $result .= @$subfield[1];
58                 $indicator = $field->indicator(1).$field->indicator(2);
59             }
60         }
61     }
62     return($indicator,$result);
63 }
64
65 sub get_item_from_barcode {
66     my ($barcode)=@_;
67     my $dbh=C4::Context->dbh;
68     my $result;
69     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
70     $rq->execute($barcode);
71     ($result)=$rq->fetchrow;
72     return($result);
73 }
74
75 sub set_item_default_location {
76     my $itemnumber = shift;
77     my $item       = Koha::Items->find($itemnumber);
78     if ( C4::Context->preference('NewItemsDefaultLocation') ) {
79         $item->permanent_location($item->location);
80         $item->location(C4::Context->preference('NewItemsDefaultLocation'));
81     }
82     else {
83         # It seems that we are dealing with that in too many places
84         $item->permanent_location($item->location) unless defined $item->permanent_location;
85     }
86     $item->store;
87 }
88
89 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
90 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
91 sub _increment_barcode {
92     my ($record, $frameworkcode) = @_;
93     my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
94     unless ($record->field($tagfield)->subfield($tagsubfield)) {
95         my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
96         $sth_barcode->execute;
97         my ($newbarcode) = $sth_barcode->fetchrow;
98         $newbarcode++;
99         # OK, we have the new barcode, now create the entry in MARC record
100         my $fieldItem = $record->field($tagfield);
101         $record->delete_field($fieldItem);
102         $fieldItem->add_subfields($tagsubfield => $newbarcode);
103         $record->insert_fields_ordered($fieldItem);
104     }
105     return $record;
106 }
107
108
109 sub generate_subfield_form {
110         my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
111   
112         my $frameworkcode = &GetFrameworkCode($biblionumber);
113
114         my %subfield_data;
115         my $dbh = C4::Context->dbh;
116         
117         my $index_subfield = int(rand(1000000)); 
118         if ($subfieldtag eq '@'){
119             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
120         } else {
121             $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
122         }
123         
124         $subfield_data{tag}        = $tag;
125         $subfield_data{subfield}   = $subfieldtag;
126         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
127         $subfield_data{mandatory}  = $subfieldlib->{mandatory};
128         $subfield_data{important}  = $subfieldlib->{important};
129         $subfield_data{repeatable} = $subfieldlib->{repeatable};
130         $subfield_data{maxlength}  = $subfieldlib->{maxlength};
131         
132         if ( ! defined( $value ) || $value eq '')  {
133             $value = $subfieldlib->{defaultvalue};
134             if ( $value ) {
135                 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
136                 my $today_dt = dt_from_string;
137                 my $year = $today_dt->strftime('%Y');
138                 my $month = $today_dt->strftime('%m');
139                 my $day = $today_dt->strftime('%d');
140                 $value =~ s/<<YYYY>>/$year/g;
141                 $value =~ s/<<MM>>/$month/g;
142                 $value =~ s/<<DD>>/$day/g;
143                 # And <<USER>> with surname (?)
144                 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
145                 $value=~s/<<USER>>/$username/g;
146             }
147         }
148
149         $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
150
151         my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
152         if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
153             foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
154                 my $CNtag       = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
155                 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
156                 my $temp2 = $temp->field($CNtag);
157
158                 next unless $temp2;
159                 $value = $temp2->as_string( $CNsubfields, ' ' );
160                 last if $value;
161             }
162         }
163
164         if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
165             my $input = new CGI;
166             $value = $input->param('barcode');
167         }
168
169         if ( $subfieldlib->{authorised_value} ) {
170             my @authorised_values;
171             my %authorised_lib;
172             # builds list, depending on authorised value...
173             if ( $subfieldlib->{authorised_value} eq "branches" ) {
174                 foreach my $thisbranch (@$branches) {
175                     push @authorised_values, $thisbranch->{branchcode};
176                     $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
177                     $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
178                 }
179             }
180             elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
181                   push @authorised_values, "";
182                   my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
183                   my $itemtypes;
184                   if($branch_limit) {
185                       $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
186                   } else {
187                       $itemtypes = Koha::ItemTypes->search_with_localization;
188                   }
189                   while ( my $itemtype = $itemtypes->next ) {
190                       push @authorised_values, $itemtype->itemtype;
191                       $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
192                   }
193
194                   unless ( $value ) {
195                       my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
196                       $itype_sth->execute( $biblionumber );
197                       ( $value ) = $itype_sth->fetchrow_array;
198                   }
199           
200                   #---- class_sources
201             }
202             elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
203                   push @authorised_values, "";
204                     
205                   my $class_sources = GetClassSources();
206                   my $default_source = C4::Context->preference("DefaultClassificationSource");
207                   
208                   foreach my $class_source (sort keys %$class_sources) {
209                       next unless $class_sources->{$class_source}->{'used'} or
210                                   ($value and $class_source eq $value)      or
211                                   ($class_source eq $default_source);
212                       push @authorised_values, $class_source;
213                       $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
214                   }
215                           $value = $default_source unless ($value);
216         
217                   #---- "true" authorised value
218             }
219             else {
220                   push @authorised_values, qq{};
221                   my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
222                   for my $r ( @$av ) {
223                       push @authorised_values, $r->{authorised_value};
224                       $authorised_lib{$r->{authorised_value}} = $r->{lib};
225                   }
226             }
227
228             if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
229                 $subfield_data{marc_value} = {
230                     type        => 'hidden',
231                     id          => $subfield_data{id},
232                     maxlength   => $subfield_data{maxlength},
233                     value       => $value,
234                 };
235             }
236             else {
237                 $subfield_data{marc_value} = {
238                     type     => 'select',
239                     id       => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
240                     values   => \@authorised_values,
241                     labels   => \%authorised_lib,
242                     default  => $value,
243                 };
244             }
245         }
246             # it's a thesaurus / authority field
247         elsif ( $subfieldlib->{authtypecode} ) {
248                 $subfield_data{marc_value} = {
249                     type         => 'text_auth',
250                     id           => $subfield_data{id},
251                     maxlength    => $subfield_data{maxlength},
252                     value        => $value,
253                     authtypecode => $subfieldlib->{authtypecode},
254                 };
255         }
256             # it's a plugin field
257         elsif ( $subfieldlib->{value_builder} ) { # plugin
258             require Koha::FrameworkPlugin;
259             my $plugin = Koha::FrameworkPlugin->new({
260                 name => $subfieldlib->{'value_builder'},
261                 item_style => 1,
262             });
263             my $pars=  { dbh => $dbh, record => $temp, tagslib =>$tagslib,
264                 id => $subfield_data{id}, tabloop => $loop_data };
265             $plugin->build( $pars );
266             if( !$plugin->errstr ) {
267                 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
268                 $subfield_data{marc_value} = {
269                     type        => 'text_plugin',
270                     id          => $subfield_data{id},
271                     maxlength   => $subfield_data{maxlength},
272                     value       => $value,
273                     class       => $class,
274                     nopopup     => $plugin->noclick,
275                     javascript  => $plugin->javascript,
276                 };
277             } else {
278                 warn $plugin->errstr;
279                 $subfield_data{marc_value} = {
280                     type        => 'text',
281                     id          => $subfield_data{id},
282                     maxlength   => $subfield_data{maxlength},
283                     value       => $value,
284                 }; # supply default input form
285             }
286         }
287         elsif ( $tag eq '' ) {       # it's an hidden field
288             $subfield_data{marc_value} = {
289                 type        => 'hidden',
290                 id          => $subfield_data{id},
291                 maxlength   => $subfield_data{maxlength},
292                 value       => $value,
293             };
294         }
295         elsif ( $subfieldlib->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
296             $subfield_data{marc_value} = {
297                 type        => 'text',
298                 id          => $subfield_data{id},
299                 maxlength   => $subfield_data{maxlength},
300                 value       => $value,
301             };
302         }
303         elsif (
304                 (
305                     $value and length($value) > 100
306                 )
307                 or (
308                     C4::Context->preference("marcflavour") eq "UNIMARC"
309                     and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
310                 )
311                 or (
312                     C4::Context->preference("marcflavour") eq "MARC21"
313                     and 500 <= $tag && $tag < 600
314                 )
315               ) {
316             # oversize field (textarea)
317             $subfield_data{marc_value} = {
318                 type        => 'textarea',
319                 id          => $subfield_data{id},
320                 value       => $value,
321             };
322         } else {
323             # it's a standard field
324             $subfield_data{marc_value} = {
325                 type        => 'text',
326                 id          => $subfield_data{id},
327                 maxlength   => $subfield_data{maxlength},
328                 value       => $value,
329             };
330         }
331
332         # Getting list of subfields to keep when restricted editing is enabled
333         my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
334         my $allowAllSubfields = (
335             not defined $subfieldsToAllowForRestrictedEditing
336               or $subfieldsToAllowForRestrictedEditing eq q||
337         ) ? 1 : 0;
338         my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
339
340         # If we're on restricted editing, and our field is not in the list of subfields to allow,
341         # then it is read-only
342         $subfield_data{marc_value}->{readonly} = (
343             not $allowAllSubfields
344             and $restrictededition
345             and !grep { $tag . '$' . $subfieldtag  eq $_ } @subfieldsToAllow
346         ) ? 1: 0;
347
348         return \%subfield_data;
349 }
350
351 # Removes some subfields when prefilling items
352 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
353 sub removeFieldsForPrefill {
354
355     my $item = shift;
356
357     # Getting item tag
358     my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
359
360     # Getting list of subfields to keep
361     my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
362
363     # Removing subfields that are not in the syspref
364     if ($tag && $subfieldsToUseWhenPrefill) {
365         my $field = $item->field($tag);
366         my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
367         foreach my $subfield ($field->subfields()) {
368             if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
369                 $field->delete_subfield(code => $subfield->[0]);
370             }
371
372         }
373     }
374
375     return $item;
376
377 }
378
379 my $input        = new CGI;
380 my $error        = $input->param('error');
381 my $biblionumber = $input->param('biblionumber');
382 my $itemnumber   = $input->param('itemnumber');
383 my $op           = $input->param('op') || q{};
384 my $hostitemnumber = $input->param('hostitemnumber');
385 my $marcflavour  = C4::Context->preference("marcflavour");
386 my $searchid     = $input->param('searchid');
387 # fast cataloguing datas
388 my $fa_circborrowernumber = $input->param('circborrowernumber');
389 my $fa_barcode            = $input->param('barcode');
390 my $fa_branch             = $input->param('branch');
391 my $fa_stickyduedate      = $input->param('stickyduedate');
392 my $fa_duedatespec        = $input->param('duedatespec');
393
394 my $frameworkcode = &GetFrameworkCode($biblionumber);
395
396 # Defining which userflag is needing according to the framework currently used
397 my $userflags;
398 if (defined $input->param('frameworkcode')) {
399     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
400 }
401
402 if (not defined $userflags) {
403     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
404 }
405
406 my ($template, $loggedinuser, $cookie)
407     = get_template_and_user({template_name => "cataloguing/additem.tt",
408                  query => $input,
409                  type => "intranet",
410                  authnotrequired => 0,
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) = AddItemFromMarc($record,$biblionumber);
600             set_item_default_location($oldbibitemnum);
601
602             # We count the item only if it was really added
603             # That way, all items are added, even if there was some already existing barcodes
604             # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
605             $i++;
606             # Only increment copynumber if item was really added
607             $copynumber++  if ( $copynumber && $copynumber =~ m/^\d+$/ );
608         }
609
610                 # Preparing the next iteration
611                 $oldbarcode = $barcodevalue;
612             }
613             undef($itemrecord);
614         }
615     }   
616     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
617         print $input->redirect(
618            '/cgi-bin/koha/circ/circulation.pl?'
619            .'borrowernumber='.$fa_circborrowernumber
620            .'&barcode='.uri_escape_utf8($fa_barcode)
621            .'&duedatespec='.$fa_duedatespec
622            .'&stickyduedate=1'
623         );
624         exit;
625     }
626
627
628 #-------------------------------------------------------------------------------
629 } elsif ($op eq "edititem") {
630 #-------------------------------------------------------------------------------
631 # retrieve item if exist => then, it's a modif
632     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
633     $nextop = "saveitem";
634 #-------------------------------------------------------------------------------
635 } elsif ($op eq "dupeitem") {
636 #-------------------------------------------------------------------------------
637 # retrieve item if exist => then, it's a modif
638     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
639     if (C4::Context->preference('autoBarcode') eq 'incremental') {
640         $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
641     }
642     else {
643         # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
644         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
645         my $fieldItem = $itemrecord->field($tagfield);
646         $itemrecord->delete_field($fieldItem);
647         $fieldItem->delete_subfields($tagsubfield);
648         $itemrecord->insert_fields_ordered($fieldItem);
649     }
650
651     #check for hidden subfield and remove them for the duplicated item
652     foreach my $field ($itemrecord->fields()){
653         my $tag = $field->{_tag};
654         foreach my $subfield ($field->subfields()){
655             my $subfieldtag = $subfield->[0];
656             if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
657             ||  abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
658                 my $fieldItem = $itemrecord->field($tag);
659                 $itemrecord->delete_field($fieldItem);
660                 $fieldItem->delete_subfields($subfieldtag);
661                 $itemrecord->insert_fields_ordered($fieldItem);
662             }
663         }
664     }
665
666     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
667     $nextop = "additem";
668 #-------------------------------------------------------------------------------
669 } elsif ($op eq "delitem") {
670 #-------------------------------------------------------------------------------
671     # check that there is no issue on this item before deletion.
672     $error = &DelItemCheck( $biblionumber,$itemnumber);
673     if($error == 1){
674         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
675     }else{
676         push @errors,$error;
677         $nextop="additem";
678     }
679 #-------------------------------------------------------------------------------
680 } elsif ($op eq "delallitems") {
681 #-------------------------------------------------------------------------------
682     my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber })->get_column('itemnumber');
683     foreach my $itemnumber ( @itemnumbers ) {
684         $error = C4::Items::DelItemCheck( $biblionumber, $itemnumber );
685         next if $error == 1; # Means ok
686         push @errors,$error;
687     }
688     if ( @errors ) {
689         $nextop="additem";
690     } else {
691         my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
692         my $views = { C4::Search::enabled_staff_search_views };
693         if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
694             print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
695         } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
696             print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
697         } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
698             print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
699         } else {
700             print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
701         }
702         exit;
703     }
704 #-------------------------------------------------------------------------------
705 } elsif ($op eq "saveitem") {
706 #-------------------------------------------------------------------------------
707     # rebuild
708     my @tags      = $input->multi_param('tag');
709     my @subfields = $input->multi_param('subfield');
710     my @values    = $input->multi_param('field_value');
711     # build indicator hash.
712     my @ind_tag   = $input->multi_param('ind_tag');
713     my @indicator = $input->multi_param('indicator');
714     # my $itemnumber = $input->param('itemnumber');
715     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
716     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
717     # MARC::Record builded => now, record in DB
718     # warn "R: ".$record->as_formatted;
719     # check that the barcode don't exist already
720     my $addedolditem = TransformMarcToKoha($itemtosave);
721     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
722     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
723         push @errors,"barcode_not_unique";
724     } else {
725         my $item = Koha::Items->find($itemnumber );
726         my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
727         $itemnumber = q{};
728         my $olditemlost = $item->itemlost;
729         my $newitemlost = $newitem->{itemlost};
730         LostItem( $item->itemnumber, 'additem' )
731             if $newitemlost && $newitemlost ge '1' && !$olditemlost;
732     }
733     $nextop="additem";
734 } elsif ($op eq "delinkitem"){
735     my $analyticfield = '773';
736         if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC'){
737         $analyticfield = '773';
738     } elsif ($marcflavour eq 'UNIMARC') {
739         $analyticfield = '461';
740     }
741     foreach my $field ($record->field($analyticfield)){
742         if ($field->subfield('9') eq $hostitemnumber){
743             $record->delete_field($field);
744             last;
745         }
746     }
747         my $modbibresult = ModBiblio($record, $biblionumber,'');
748 }
749
750 #
751 #-------------------------------------------------------------------------------
752 # build screen with existing items. and "new" one
753 #-------------------------------------------------------------------------------
754
755 # now, build existiing item list
756 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
757 #my @fields = $record->fields();
758
759
760 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
761 my @big_array;
762 #---- finds where items.itemnumber is stored
763 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
764 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
765 C4::Biblio::EmbedItemsInMarcBiblio({
766     marc_record  => $temp,
767     biblionumber => $biblionumber });
768 my @fields = $temp->fields();
769
770
771 my @hostitemnumbers;
772 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
773     my $analyticfield = '773';
774     if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC') {
775         $analyticfield = '773';
776     } elsif ($marcflavour eq 'UNIMARC') {
777         $analyticfield = '461';
778     }
779     foreach my $hostfield ($temp->field($analyticfield)){
780         my $hostbiblionumber = $hostfield->subfield('0');
781         if ($hostbiblionumber){
782             my $hostrecord = GetMarcBiblio({
783                 biblionumber => $hostbiblionumber,
784                 embed_items  => 1 });
785             if ($hostrecord) {
786                 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
787                 foreach my $hostitem ($hostrecord->field($itemfield)){
788                     if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
789                         push (@fields, $hostitem);
790                         push (@hostitemnumbers, $hostfield->subfield('9'));
791                     }
792                 }
793             }
794         }
795     }
796 }
797
798 foreach my $field (@fields) {
799     next if ( $field->tag() < 10 );
800
801     my @subf = $field->subfields or ();    # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
802     my %this_row;
803     # loop through each subfield
804     my $i = 0;
805     foreach my $subfield (@subf){
806         my $subfieldcode = $subfield->[0];
807         my $subfieldvalue= $subfield->[1];
808
809         next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10 
810                 && ($field->tag() ne $itemtagfield 
811                 && $subfieldcode   ne $itemtagsubfield));
812         $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10);
813                 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10) {
814                     $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
815                 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
816                         $subfieldcode, $subfieldvalue, '', $tagslib) 
817                                                 || $subfieldvalue;
818         }
819
820         if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
821             #verifying rights
822             my $userenv = C4::Context->userenv();
823             unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
824                 $this_row{'nomod'} = 1;
825             }
826         }
827         $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
828
829         if ( C4::Context->preference('EasyAnalyticalRecords') ) {
830             foreach my $hostitemnumber (@hostitemnumbers) {
831                 my $item = Koha::Items->find( $hostitemnumber );
832                 if ($this_row{itemnumber} eq $hostitemnumber) {
833                     $this_row{hostitemflag} = 1;
834                     $this_row{hostbiblionumber}= $item->biblio->biblionumber;
835                     last;
836                 }
837             }
838         }
839     }
840     if (%this_row) {
841         push(@big_array, \%this_row);
842     }
843 }
844
845 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
846 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
847
848 # now, construct template !
849 # First, the existing items for display
850 my @item_value_loop;
851 my @header_value_loop;
852 for my $row ( @big_array ) {
853     my %row_data;
854     my @item_fields;
855     foreach my $key (sort keys %witness){
856         my $item_field;
857         if ( $row->{$key} ){
858             $item_field->{field} = $row->{$key};
859         } else {
860             $item_field->{field} = '';
861         }
862
863         for my $kohafield (
864             qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
865           )
866         {
867             my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
868             next unless $key eq $subfield;
869             $item_field->{field} = output_pref( { str => $row->{$key}, dateonly => 1 } );
870         }
871
872         push @item_fields, $item_field;
873     }
874     $row_data{item_value} = [ @item_fields ];
875     $row_data{itemnumber} = $row->{itemnumber};
876     #reporting this_row values
877     $row_data{'nomod'} = $row->{'nomod'};
878     $row_data{'hostitemflag'} = $row->{'hostitemflag'};
879     $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
880 #       $row_data{'countanalytics'} = $row->{'countanalytics'};
881     push(@item_value_loop,\%row_data);
882 }
883 foreach my $subfield_code (sort keys(%witness)) {
884     my %header_value;
885     $header_value{header_value} = $witness{$subfield_code};
886
887     my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
888     my $kohafield = $subfieldlib->{kohafield};
889     if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
890         $header_value{column_name} = $1;
891     }
892
893     push(@header_value_loop, \%header_value);
894 }
895
896 # now, build the item form for entering a new item
897 my @loop_data =();
898 my $i=0;
899
900 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
901 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
902 for my $library ( @$libraries ) {
903     $library->{selected} = 1 if $library->{branchcode} eq $branch
904 }
905
906 # We generate form, from actuel record
907 @fields = ();
908 if($itemrecord){
909     foreach my $field ($itemrecord->fields()){
910         my $tag = $field->{_tag};
911         foreach my $subfield ( $field->subfields() ){
912
913             my $subfieldtag = $subfield->[0];
914             my $value       = $subfield->[1];
915             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
916
917             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
918
919             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
920             push @fields, "$tag$subfieldtag";
921             push (@loop_data, $subfield_data);
922             $i++;
923                     }
924
925                 }
926             }
927     # and now we add fields that are empty
928
929 # Using last created item if it exists
930
931 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
932
933 # We generate form, and fill with values if defined
934 foreach my $tag ( keys %{$tagslib}){
935     foreach my $subtag (keys %{$tagslib->{$tag}}){
936         next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
937         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
938         next if any { /^$tag$subtag$/ }  @fields;
939
940         my @values = (undef);
941         @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
942         for my $value (@values){
943             my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
944             push (@loop_data, $subfield_data);
945             $i++;
946         }
947   }
948 }
949 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
950
951 my $item = Koha::Items->find($itemnumber); # We certainly want to fetch it earlier
952
953 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
954 $template->param(
955     biblionumber => $biblionumber,
956     title        => $oldrecord->{title},
957     author       => $oldrecord->{author},
958     item_loop        => \@item_value_loop,
959     item_header_loop => \@header_value_loop,
960     item             => \@loop_data,
961     itemnumber       => $itemnumber,
962     barcode          => $item ? $item->barcode : undef,
963     itemtagfield     => $itemtagfield,
964     itemtagsubfield  => $itemtagsubfield,
965     op      => $nextop,
966     popup => scalar $input->param('popup') ? 1: 0,
967     C4::Search::enabled_staff_search_views,
968 );
969 $template->{'VARS'}->{'searchid'} = $searchid;
970
971 if ($frameworkcode eq 'FA'){
972     # fast cataloguing datas
973     $template->param(
974         'circborrowernumber' => $fa_circborrowernumber,
975         'barcode'            => $fa_barcode,
976         'branch'             => $fa_branch,
977         'stickyduedate'      => $fa_stickyduedate,
978         'duedatespec'        => $fa_duedatespec,
979     );
980 }
981
982 foreach my $error (@errors) {
983     $template->param($error => 1);
984 }
985 output_html_with_http_headers $input, $cookie, $template->output;