Bug 21986: Do not escape quotation marks when cataloguing
[koha.git] / cataloguing / additem.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2004-2010 BibLibre
5 # Parts Copyright Catalyst IT 2011
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 use Modern::Perl;
23
24 use CGI qw ( -utf8 );
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Context;
30 use C4::Circulation;
31 use C4::Koha;
32 use C4::ClassSource;
33 use Koha::DateUtils;
34 use Koha::Items;
35 use Koha::ItemTypes;
36 use Koha::Libraries;
37 use Koha::Patrons;
38 use List::MoreUtils qw/any/;
39 use C4::Search;
40 use Storable qw(thaw freeze);
41 use URI::Escape;
42 use C4::Members;
43
44 use MARC::File::XML;
45 use URI::Escape;
46
47 our $dbh = C4::Context->dbh;
48
49 sub find_value {
50     my ($tagfield,$insubfield,$record) = @_;
51     my $result;
52     my $indicator;
53     foreach my $field ($record->field($tagfield)) {
54         my @subfields = $field->subfields();
55         foreach my $subfield (@subfields) {
56             if (@$subfield[0] eq $insubfield) {
57                 $result .= @$subfield[1];
58                 $indicator = $field->indicator(1).$field->indicator(2);
59             }
60         }
61     }
62     return($indicator,$result);
63 }
64
65 sub get_item_from_barcode {
66     my ($barcode)=@_;
67     my $dbh=C4::Context->dbh;
68     my $result;
69     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
70     $rq->execute($barcode);
71     ($result)=$rq->fetchrow;
72     return($result);
73 }
74
75 sub set_item_default_location {
76     my $itemnumber = shift;
77     my $item = GetItem( $itemnumber );
78     if ( C4::Context->preference('NewItemsDefaultLocation') ) {
79         $item->{'permanent_location'} = $item->{'location'};
80         $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
81         ModItem( $item, undef, $itemnumber);
82     }
83     else {
84       $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
85       ModItem( $item, undef, $itemnumber);
86     }
87 }
88
89 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
90 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
91 sub _increment_barcode {
92     my ($record, $frameworkcode) = @_;
93     my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
94     unless ($record->field($tagfield)->subfield($tagsubfield)) {
95         my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
96         $sth_barcode->execute;
97         my ($newbarcode) = $sth_barcode->fetchrow;
98         $newbarcode++;
99         # OK, we have the new barcode, now create the entry in MARC record
100         my $fieldItem = $record->field($tagfield);
101         $record->delete_field($fieldItem);
102         $fieldItem->add_subfields($tagsubfield => $newbarcode);
103         $record->insert_fields_ordered($fieldItem);
104     }
105     return $record;
106 }
107
108
109 sub generate_subfield_form {
110         my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
111   
112         my $frameworkcode = &GetFrameworkCode($biblionumber);
113
114         my %subfield_data;
115         my $dbh = C4::Context->dbh;
116         
117         my $index_subfield = int(rand(1000000)); 
118         if ($subfieldtag eq '@'){
119             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
120         } else {
121             $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
122         }
123         
124         $subfield_data{tag}        = $tag;
125         $subfield_data{subfield}   = $subfieldtag;
126         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
127         $subfield_data{mandatory}  = $subfieldlib->{mandatory};
128         $subfield_data{repeatable} = $subfieldlib->{repeatable};
129         $subfield_data{maxlength}  = $subfieldlib->{maxlength};
130         
131         if ( ! defined( $value ) || $value eq '')  {
132             $value = $subfieldlib->{defaultvalue};
133             if ( $value ) {
134                 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
135                 my $today_dt = dt_from_string;
136                 my $year = $today_dt->strftime('%Y');
137                 my $month = $today_dt->strftime('%m');
138                 my $day = $today_dt->strftime('%d');
139                 $value =~ s/<<YYYY>>/$year/g;
140                 $value =~ s/<<MM>>/$month/g;
141                 $value =~ s/<<DD>>/$day/g;
142                 # And <<USER>> with surname (?)
143                 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
144                 $value=~s/<<USER>>/$username/g;
145             }
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 = join ' ', $temp2->subfield($CNsubfield) || q{}, $temp2->subfield($CNsubfield2) || q{};
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, "";
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, "";
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{};
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{maxlength},
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{maxlength},
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{maxlength},
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{maxlength},
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{maxlength},
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{maxlength},
293                 value       => $value,
294             };
295         }
296         elsif (
297                 (
298                     $value and length($value) > 100
299                 )
300                 or (
301                     C4::Context->preference("marcflavour") eq "UNIMARC"
302                     and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
303                 )
304                 or (
305                     C4::Context->preference("marcflavour") eq "MARC21"
306                     and 500 <= $tag && $tag < 600
307                 )
308               ) {
309             # oversize field (textarea)
310             $subfield_data{marc_value} = {
311                 type        => 'textarea',
312                 id          => $subfield_data{id},
313                 value       => $value,
314             };
315         } else {
316             # it's a standard field
317             $subfield_data{marc_value} = {
318                 type        => 'text',
319                 id          => $subfield_data{id},
320                 maxlength   => $subfield_data{maxlength},
321                 value       => $value,
322             };
323         }
324
325         # Getting list of subfields to keep when restricted editing is enabled
326         my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
327         my $allowAllSubfields = (
328             not defined $subfieldsToAllowForRestrictedEditing
329               or $subfieldsToAllowForRestrictedEditing eq q||
330         ) ? 1 : 0;
331         my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
332
333         # If we're on restricted editing, and our field is not in the list of subfields to allow,
334         # then it is read-only
335         $subfield_data{marc_value}->{readonly} = (
336             not $allowAllSubfields
337             and $restrictededition
338             and !grep { $tag . '$' . $subfieldtag  eq $_ } @subfieldsToAllow
339         ) ? 1: 0;
340
341         return \%subfield_data;
342 }
343
344 # Removes some subfields when prefilling items
345 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
346 sub removeFieldsForPrefill {
347
348     my $item = shift;
349
350     # Getting item tag
351     my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
352
353     # Getting list of subfields to keep
354     my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
355
356     # Removing subfields that are not in the syspref
357     if ($tag && $subfieldsToUseWhenPrefill) {
358         my $field = $item->field($tag);
359         my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
360         foreach my $subfield ($field->subfields()) {
361             if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
362                 $field->delete_subfield(code => $subfield->[0]);
363             }
364
365         }
366     }
367
368     return $item;
369
370 }
371
372 my $input        = new CGI;
373 my $error        = $input->param('error');
374 my $biblionumber = $input->param('biblionumber');
375 my $itemnumber   = $input->param('itemnumber');
376 my $op           = $input->param('op') || q{};
377 my $hostitemnumber = $input->param('hostitemnumber');
378 my $marcflavour  = C4::Context->preference("marcflavour");
379 my $searchid     = $input->param('searchid');
380 # fast cataloguing datas
381 my $fa_circborrowernumber = $input->param('circborrowernumber');
382 my $fa_barcode            = $input->param('barcode');
383 my $fa_branch             = $input->param('branch');
384 my $fa_stickyduedate      = $input->param('stickyduedate');
385 my $fa_duedatespec        = $input->param('duedatespec');
386
387 my $frameworkcode = &GetFrameworkCode($biblionumber);
388
389 # Defining which userflag is needing according to the framework currently used
390 my $userflags;
391 if (defined $input->param('frameworkcode')) {
392     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
393 }
394
395 if (not defined $userflags) {
396     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
397 }
398
399 my ($template, $loggedinuser, $cookie)
400     = get_template_and_user({template_name => "cataloguing/additem.tt",
401                  query => $input,
402                  type => "intranet",
403                  authnotrequired => 0,
404                  flagsrequired => {editcatalogue => $userflags},
405                  debug => 1,
406                  });
407
408
409 # Does the user have a restricted item editing permission?
410 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
411 my $restrictededition = $uid ? haspermission($uid,  {'editcatalogue' => 'edit_items_restricted'}) : undef;
412 # In case user is a superlibrarian, editing is not restricted
413 $restrictededition = 0 if ($restrictededition != 0 &&  C4::Context->IsSuperLibrarian());
414 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
415 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
416
417 my $tagslib = &GetMarcStructure(1,$frameworkcode);
418 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
419 my $oldrecord = TransformMarcToKoha($record);
420 my $itemrecord;
421 my $nextop="additem";
422 my @errors; # store errors found while checking data BEFORE saving item.
423
424 # Getting last created item cookie
425 my $prefillitem = C4::Context->preference('PrefillItem');
426 my $justaddeditem;
427 my $cookieitemrecord;
428 if ($prefillitem) {
429     my $lastitemcookie = $input->cookie('LastCreatedItem');
430     if ($lastitemcookie) {
431         $lastitemcookie = uri_unescape($lastitemcookie);
432         eval {
433             if ( thaw($lastitemcookie) ) {
434                 $cookieitemrecord = thaw($lastitemcookie);
435                 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
436             }
437         };
438         if ($@) {
439             $lastitemcookie = 'undef' unless $lastitemcookie;
440             warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
441         }
442     }
443 }
444
445 #-------------------------------------------------------------------------------
446 if ($op eq "additem") {
447
448     #-------------------------------------------------------------------------------
449     # rebuild
450     my @tags      = $input->multi_param('tag');
451     my @subfields = $input->multi_param('subfield');
452     my @values    = $input->multi_param('field_value');
453     # build indicator hash.
454     my @ind_tag   = $input->multi_param('ind_tag');
455     my @indicator = $input->multi_param('indicator');
456     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
457     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
458
459     # type of add
460     my $add_submit                 = $input->param('add_submit');
461     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
462     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
463     my $number_of_copies           = $input->param('number_of_copies');
464
465     # This is a bit tricky : if there is a cookie for the last created item and
466     # we just added an item, the cookie value is not correct yet (it will be updated
467     # next page). To prevent the form from being filled with outdated values, we
468     # force the use of "add and duplicate" feature, so the form will be filled with
469     # correct values.
470     $add_duplicate_submit = 1 if ($prefillitem);
471     $justaddeditem = 1;
472
473     # if autoBarcode is set to 'incremental', calculate barcode...
474     if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
475         $record = _increment_barcode($record, $frameworkcode);
476     }
477
478     my $addedolditem = TransformMarcToKoha( $record );
479
480     # If we have to add or add & duplicate, we add the item
481     if ( $add_submit || $add_duplicate_submit ) {
482
483         # check for item barcode # being unique
484         my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
485         push @errors, "barcode_not_unique" if ($exist_itemnumber);
486
487         # if barcode exists, don't create, but report The problem.
488         unless ($exist_itemnumber) {
489             my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
490             set_item_default_location($oldbibitemnum);
491
492             # Pushing the last created item cookie back
493             if ($prefillitem && defined $record) {
494                 my $itemcookie = $input->cookie(
495                     -name => 'LastCreatedItem',
496                     # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
497                     -value   => uri_escape_utf8( freeze( $record ) ),
498                     -HttpOnly => 1,
499                     -expires => ''
500                 );
501
502                 $cookie = [ $cookie, $itemcookie ];
503             }
504
505         }
506         $nextop = "additem";
507         if ($exist_itemnumber) {
508             $itemrecord = $record;
509         }
510     }
511
512     # If we have to add & duplicate
513     if ($add_duplicate_submit) {
514         $itemrecord = $record;
515         if (C4::Context->preference('autoBarcode') eq 'incremental') {
516             $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
517         }
518         else {
519             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
520             my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
521             my $fieldItem = $itemrecord->field($tagfield);
522             $itemrecord->delete_field($fieldItem);
523             $fieldItem->delete_subfields($tagsubfield);
524             $itemrecord->insert_fields_ordered($fieldItem);
525         }
526     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
527     }
528
529     # If we have to add multiple copies
530     if ($add_multiple_copies_submit) {
531
532         use C4::Barcodes;
533         my $barcodeobj = C4::Barcodes->new;
534         my $oldbarcode = $addedolditem->{'barcode'};
535         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
536
537     # If there is a barcode and we can't find their new values, we can't add multiple copies
538         my $testbarcode;
539         $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
540         if ($oldbarcode && !$testbarcode) {
541
542             push @errors, "no_next_barcode";
543             $itemrecord = $record;
544
545         } else {
546         # We add each item
547
548             # For the first iteration
549             my $barcodevalue = $oldbarcode;
550             my $exist_itemnumber;
551
552
553             for (my $i = 0; $i < $number_of_copies;) {
554
555                 # If there is a barcode
556                 if ($barcodevalue) {
557
558                     # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
559                     $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
560
561                     # Putting it into the record
562                     if ($barcodevalue) {
563                         $record->field($tagfield)->update($tagsubfield => $barcodevalue);
564                     }
565
566                     # Checking if the barcode already exists
567                     $exist_itemnumber = get_item_from_barcode($barcodevalue);
568                 }
569
570                 # Adding the item
571         if (!$exist_itemnumber) {
572             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
573             set_item_default_location($oldbibitemnum);
574
575             # We count the item only if it was really added
576             # That way, all items are added, even if there was some already existing barcodes
577             # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
578             $i++;
579         }
580
581                 # Preparing the next iteration
582                 $oldbarcode = $barcodevalue;
583             }
584             undef($itemrecord);
585         }
586     }   
587     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
588         print $input->redirect(
589            '/cgi-bin/koha/circ/circulation.pl?'
590            .'borrowernumber='.$fa_circborrowernumber
591            .'&barcode='.uri_escape_utf8($fa_barcode)
592            .'&duedatespec='.$fa_duedatespec
593            .'&stickyduedate=1'
594         );
595         exit;
596     }
597
598
599 #-------------------------------------------------------------------------------
600 } elsif ($op eq "edititem") {
601 #-------------------------------------------------------------------------------
602 # retrieve item if exist => then, it's a modif
603     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
604     $nextop = "saveitem";
605 #-------------------------------------------------------------------------------
606 } elsif ($op eq "dupeitem") {
607 #-------------------------------------------------------------------------------
608 # retrieve item if exist => then, it's a modif
609     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
610     if (C4::Context->preference('autoBarcode') eq 'incremental') {
611         $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
612     }
613     else {
614         # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
615         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
616         my $fieldItem = $itemrecord->field($tagfield);
617         $itemrecord->delete_field($fieldItem);
618         $fieldItem->delete_subfields($tagsubfield);
619         $itemrecord->insert_fields_ordered($fieldItem);
620     }
621
622     #check for hidden subfield and remove them for the duplicated item
623     foreach my $field ($itemrecord->fields()){
624         my $tag = $field->{_tag};
625         foreach my $subfield ($field->subfields()){
626             my $subfieldtag = $subfield->[0];
627             if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
628             ||  abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
629                 my $fieldItem = $itemrecord->field($tag);
630                 $itemrecord->delete_field($fieldItem);
631                 $fieldItem->delete_subfields($subfieldtag);
632                 $itemrecord->insert_fields_ordered($fieldItem);
633             }
634         }
635     }
636
637     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
638     $nextop = "additem";
639 #-------------------------------------------------------------------------------
640 } elsif ($op eq "delitem") {
641 #-------------------------------------------------------------------------------
642     # check that there is no issue on this item before deletion.
643     $error = &DelItemCheck( $biblionumber,$itemnumber);
644     if($error == 1){
645         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
646     }else{
647         push @errors,$error;
648         $nextop="additem";
649     }
650 #-------------------------------------------------------------------------------
651 } elsif ($op eq "delallitems") {
652 #-------------------------------------------------------------------------------
653     my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber })->get_column('itemnumber');
654     foreach my $itemnumber ( @itemnumbers ) {
655         $error = C4::Items::DelItemCheck( $biblionumber, $itemnumber );
656         next if $error == 1; # Means ok
657         push @errors,$error;
658     }
659     if ( @errors ) {
660         $nextop="additem";
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 } elsif ($op eq "saveitem") {
677 #-------------------------------------------------------------------------------
678     # rebuild
679     my @tags      = $input->multi_param('tag');
680     my @subfields = $input->multi_param('subfield');
681     my @values    = $input->multi_param('field_value');
682     # build indicator hash.
683     my @ind_tag   = $input->multi_param('ind_tag');
684     my @indicator = $input->multi_param('indicator');
685     # my $itemnumber = $input->param('itemnumber');
686     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
687     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
688     # MARC::Record builded => now, record in DB
689     # warn "R: ".$record->as_formatted;
690     # check that the barcode don't exist already
691     my $addedolditem = TransformMarcToKoha($itemtosave);
692     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
693     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
694         push @errors,"barcode_not_unique";
695     } else {
696         my $item = GetItem( $itemnumber );
697         my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
698         $itemnumber = q{};
699         my $olditemlost = $item->{itemlost};
700         my $newitemlost = $newitem->{itemlost};
701         LostItem( $item->{itemnumber}, 'additem' )
702             if $newitemlost && $newitemlost ge '1' && !$olditemlost;
703     }
704     $nextop="additem";
705 } elsif ($op eq "delinkitem"){
706     my $analyticfield = '773';
707         if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC'){
708         $analyticfield = '773';
709     } elsif ($marcflavour eq 'UNIMARC') {
710         $analyticfield = '461';
711     }
712     foreach my $field ($record->field($analyticfield)){
713         if ($field->subfield('9') eq $hostitemnumber){
714             $record->delete_field($field);
715             last;
716         }
717     }
718         my $modbibresult = ModBiblio($record, $biblionumber,'');
719 }
720
721 #
722 #-------------------------------------------------------------------------------
723 # build screen with existing items. and "new" one
724 #-------------------------------------------------------------------------------
725
726 # now, build existiing item list
727 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
728 #my @fields = $record->fields();
729
730
731 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
732 my @big_array;
733 #---- finds where items.itemnumber is stored
734 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
735 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
736 C4::Biblio::EmbedItemsInMarcBiblio({
737     marc_record  => $temp,
738     biblionumber => $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     }
812     if (%this_row) {
813         push(@big_array, \%this_row);
814     }
815 }
816
817 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
818 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
819
820 # now, construct template !
821 # First, the existing items for display
822 my @item_value_loop;
823 my @header_value_loop;
824 for my $row ( @big_array ) {
825     my %row_data;
826     my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
827     $row_data{item_value} = [ @item_fields ];
828     $row_data{itemnumber} = $row->{itemnumber};
829     #reporting this_row values
830     $row_data{'nomod'} = $row->{'nomod'};
831     $row_data{'hostitemflag'} = $row->{'hostitemflag'};
832     $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
833 #       $row_data{'countanalytics'} = $row->{'countanalytics'};
834     push(@item_value_loop,\%row_data);
835 }
836 foreach my $subfield_code (sort keys(%witness)) {
837     my %header_value;
838     $header_value{header_value} = $witness{$subfield_code};
839
840     my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
841     my $kohafield = $subfieldlib->{kohafield};
842     if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
843         $header_value{column_name} = $1;
844     }
845
846     push(@header_value_loop, \%header_value);
847 }
848
849 # now, build the item form for entering a new item
850 my @loop_data =();
851 my $i=0;
852
853 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
854
855 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
856 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
857 for my $library ( @$libraries ) {
858     $library->{selected} = 1 if $library->{branchcode} eq $branch
859 }
860
861 # We generate form, from actuel record
862 @fields = ();
863 if($itemrecord){
864     foreach my $field ($itemrecord->fields()){
865         my $tag = $field->{_tag};
866         foreach my $subfield ( $field->subfields() ){
867
868             my $subfieldtag = $subfield->[0];
869             my $value       = $subfield->[1];
870             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
871
872             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
873
874             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
875             push @fields, "$tag$subfieldtag";
876             push (@loop_data, $subfield_data);
877             $i++;
878                     }
879
880                 }
881             }
882     # and now we add fields that are empty
883
884 # Using last created item if it exists
885
886 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
887
888 # We generate form, and fill with values if defined
889 foreach my $tag ( keys %{$tagslib}){
890     foreach my $subtag (keys %{$tagslib->{$tag}}){
891         next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
892         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
893         next if any { /^$tag$subtag$/ }  @fields;
894
895         my @values = (undef);
896         @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
897         for my $value (@values){
898             my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
899             push (@loop_data, $subfield_data);
900             $i++;
901         }
902   }
903 }
904 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
905
906 my $item = Koha::Items->find($itemnumber); # We certainly want to fetch it earlier
907
908 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
909 $template->param(
910     biblionumber => $biblionumber,
911     title        => $oldrecord->{title},
912     author       => $oldrecord->{author},
913     item_loop        => \@item_value_loop,
914     item_header_loop => \@header_value_loop,
915     item             => \@loop_data,
916     itemnumber       => $itemnumber,
917     barcode          => $item ? $item->barcode : undef,
918     itemtagfield     => $itemtagfield,
919     itemtagsubfield  => $itemtagsubfield,
920     op      => $nextop,
921     opisadd => ($nextop eq "saveitem") ? 0 : 1,
922     popup => scalar $input->param('popup') ? 1: 0,
923     C4::Search::enabled_staff_search_views,
924 );
925 $template->{'VARS'}->{'searchid'} = $searchid;
926
927 if ($frameworkcode eq 'FA'){
928     # fast cataloguing datas
929     $template->param(
930         'circborrowernumber' => $fa_circborrowernumber,
931         'barcode'            => $fa_barcode,
932         'branch'             => $fa_branch,
933         'stickyduedate'      => $fa_stickyduedate,
934         'duedatespec'        => $fa_duedatespec,
935     );
936 }
937
938 foreach my $error (@errors) {
939     $template->param($error => 1);
940 }
941 output_html_with_http_headers $input, $cookie, $template->output;