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