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