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