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