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