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