3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2004-2010 BibLibre
5 # Parts Copyright Catalyst IT 2011
7 # This file is part of Koha.
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.
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.
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>.
38 use Koha::SearchEngine::Indexer;
39 use List::MoreUtils qw/any/;
41 use Storable qw(thaw freeze);
47 use MIME::Base64 qw(decode_base64url encode_base64url);
49 our $dbh = C4::Context->dbh;
52 my ($tagfield,$insubfield,$record) = @_;
55 foreach my $field ($record->field($tagfield)) {
56 my @subfields = $field->subfields();
57 foreach my $subfield (@subfields) {
58 if (@$subfield[0] eq $insubfield) {
59 $result .= @$subfield[1];
60 $indicator = $field->indicator(1).$field->indicator(2);
64 return($indicator,$result);
67 sub get_item_from_barcode {
69 my $dbh=C4::Context->dbh;
71 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
72 $rq->execute($barcode);
73 ($result)=$rq->fetchrow;
77 sub set_item_default_location {
78 my $itemnumber = shift;
79 my $item = Koha::Items->find($itemnumber);
80 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
81 $item->permanent_location($item->location);
82 $item->location(C4::Context->preference('NewItemsDefaultLocation'));
85 # It seems that we are dealing with that in too many places
86 $item->permanent_location($item->location) unless defined $item->permanent_location;
91 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
92 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
93 sub _increment_barcode {
94 my ($record, $frameworkcode) = @_;
95 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
96 unless ($record->field($tagfield)->subfield($tagsubfield)) {
97 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
98 $sth_barcode->execute;
99 my ($newbarcode) = $sth_barcode->fetchrow;
101 # OK, we have the new barcode, now create the entry in MARC record
102 my $fieldItem = $record->field($tagfield);
103 $record->delete_field($fieldItem);
104 $fieldItem->add_subfields($tagsubfield => $newbarcode);
105 $record->insert_fields_ordered($fieldItem);
111 sub generate_subfield_form {
112 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition, $item) = @_;
114 my $frameworkcode = &GetFrameworkCode($biblionumber);
117 my $dbh = C4::Context->dbh;
119 my $index_subfield = int(rand(1000000));
120 if ($subfieldtag eq '@'){
121 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
123 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
126 $subfield_data{tag} = $tag;
127 $subfield_data{subfield} = $subfieldtag;
128 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
129 $subfield_data{mandatory} = $subfieldlib->{mandatory};
130 $subfield_data{important} = $subfieldlib->{important};
131 $subfield_data{repeatable} = $subfieldlib->{repeatable};
132 $subfield_data{maxlength} = $subfieldlib->{maxlength};
134 if ( ! defined( $value ) || $value eq '') {
135 $value = $subfieldlib->{defaultvalue};
137 # get today date & replace <<YYYY>>, <<YY>>, <<MM>>, <<DD>> if provided in the default value
138 my $today_dt = dt_from_string;
139 my $year = $today_dt->strftime('%Y');
140 my $shortyear = $today_dt->strftime('%y');
141 my $month = $today_dt->strftime('%m');
142 my $day = $today_dt->strftime('%d');
143 $value =~ s/<<YYYY>>/$year/g;
144 $value =~ s/<<YY>>/$shortyear/g;
145 $value =~ s/<<MM>>/$month/g;
146 $value =~ s/<<DD>>/$day/g;
147 # And <<USER>> with surname (?)
148 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
149 $value=~s/<<USER>>/$username/g;
153 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
155 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
156 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
157 foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
158 my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
159 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
160 my $temp2 = $temp->field($CNtag);
163 $value = $temp2->as_string( $CNsubfields, ' ' );
168 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
169 my $input = CGI->new;
170 $value = $input->param('barcode');
173 if ( $subfieldlib->{authorised_value} ) {
174 my @authorised_values;
176 # builds list, depending on authorised value...
177 if ( $subfieldlib->{authorised_value} eq "LOST" ) {
178 my $ClaimReturnedLostValue = C4::Context->preference('ClaimReturnedLostValue');
179 my $item_is_return_claim = $ClaimReturnedLostValue && $item && $item->itemlost && $ClaimReturnedLostValue eq $item->itemlost;
180 $subfield_data{IS_RETURN_CLAIM} = $item_is_return_claim;
182 $subfield_data{IS_LOST_AV} = 1;
184 push @authorised_values, qq{};
185 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
187 push @authorised_values, $r->{authorised_value};
188 $authorised_lib{$r->{authorised_value}} = $r->{lib};
191 elsif ( $subfieldlib->{authorised_value} eq "branches" ) {
192 foreach my $thisbranch (@$branches) {
193 push @authorised_values, $thisbranch->{branchcode};
194 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
195 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
198 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
199 push @authorised_values, "";
200 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
203 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
205 $itemtypes = Koha::ItemTypes->search_with_localization;
207 while ( my $itemtype = $itemtypes->next ) {
208 push @authorised_values, $itemtype->itemtype;
209 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
213 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
214 $itype_sth->execute( $biblionumber );
215 ( $value ) = $itype_sth->fetchrow_array;
220 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
221 push @authorised_values, "";
223 my $class_sources = GetClassSources();
224 my $default_source = C4::Context->preference("DefaultClassificationSource");
226 foreach my $class_source (sort keys %$class_sources) {
227 next unless $class_sources->{$class_source}->{'used'} or
228 ($value and $class_source eq $value) or
229 ($class_source eq $default_source);
230 push @authorised_values, $class_source;
231 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
233 $value = $default_source unless ($value);
235 #---- "true" authorised value
238 push @authorised_values, qq{};
239 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
241 push @authorised_values, $r->{authorised_value};
242 $authorised_lib{$r->{authorised_value}} = $r->{lib};
246 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
247 $subfield_data{marc_value} = {
249 id => $subfield_data{id},
250 maxlength => $subfield_data{maxlength},
252 ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
256 $subfield_data{marc_value} = {
258 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
259 values => \@authorised_values,
260 labels => \%authorised_lib,
262 ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
266 # it's a thesaurus / authority field
267 elsif ( $subfieldlib->{authtypecode} ) {
268 $subfield_data{marc_value} = {
270 id => $subfield_data{id},
271 maxlength => $subfield_data{maxlength},
273 authtypecode => $subfieldlib->{authtypecode},
276 # it's a plugin field
277 elsif ( $subfieldlib->{value_builder} ) { # plugin
278 require Koha::FrameworkPlugin;
279 my $plugin = Koha::FrameworkPlugin->new({
280 name => $subfieldlib->{'value_builder'},
283 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
284 id => $subfield_data{id}, tabloop => $loop_data };
285 $plugin->build( $pars );
286 if( !$plugin->errstr ) {
287 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
288 $subfield_data{marc_value} = {
289 type => 'text_plugin',
290 id => $subfield_data{id},
291 maxlength => $subfield_data{maxlength},
294 nopopup => $plugin->noclick,
295 javascript => $plugin->javascript,
298 warn $plugin->errstr;
299 $subfield_data{marc_value} = {
301 id => $subfield_data{id},
302 maxlength => $subfield_data{maxlength},
304 }; # supply default input form
307 elsif ( $tag eq '' ) { # it's an hidden field
308 $subfield_data{marc_value} = {
310 id => $subfield_data{id},
311 maxlength => $subfield_data{maxlength},
315 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
316 $subfield_data{marc_value} = {
318 id => $subfield_data{id},
319 maxlength => $subfield_data{maxlength},
325 $value and length($value) > 100
328 C4::Context->preference("marcflavour") eq "UNIMARC"
329 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
332 C4::Context->preference("marcflavour") eq "MARC21"
333 and 500 <= $tag && $tag < 600
336 # oversize field (textarea)
337 $subfield_data{marc_value} = {
339 id => $subfield_data{id},
343 # it's a standard field
344 $subfield_data{marc_value} = {
346 id => $subfield_data{id},
347 maxlength => $subfield_data{maxlength},
352 # Getting list of subfields to keep when restricted editing is enabled
353 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
354 my $allowAllSubfields = (
355 not defined $subfieldsToAllowForRestrictedEditing
356 or $subfieldsToAllowForRestrictedEditing eq q||
358 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
360 # If we're on restricted editing, and our field is not in the list of subfields to allow,
361 # then it is read-only
362 $subfield_data{marc_value}->{readonly} = (
363 not $allowAllSubfields
364 and $restrictededition
365 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
368 return \%subfield_data;
371 # Removes some subfields when prefilling items
372 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
373 sub removeFieldsForPrefill {
378 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
380 # Getting list of subfields to keep
381 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
383 # Removing subfields that are not in the syspref
384 if ($tag && $subfieldsToUseWhenPrefill) {
385 my $field = $item->field($tag);
386 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
387 foreach my $subfield ($field->subfields()) {
388 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
389 $field->delete_subfield(code => $subfield->[0]);
399 my $input = CGI->new;
400 my $error = $input->param('error');
404 if( $input->param('itemnumber') && !$input->param('biblionumber') ){
405 $itemnumber = $input->param('itemnumber');
406 my $item = Koha::Items->find( $itemnumber );
407 $biblionumber = $item->biblionumber;
409 $biblionumber = $input->param('biblionumber');
410 $itemnumber = $input->param('itemnumber');
413 my $op = $input->param('op') || q{};
414 my $hostitemnumber = $input->param('hostitemnumber');
415 my $marcflavour = C4::Context->preference("marcflavour");
416 my $searchid = $input->param('searchid');
417 # fast cataloguing datas
418 my $fa_circborrowernumber = $input->param('circborrowernumber');
419 my $fa_barcode = $input->param('barcode');
420 my $fa_branch = $input->param('branch');
421 my $fa_stickyduedate = $input->param('stickyduedate');
422 my $fa_duedatespec = $input->param('duedatespec');
424 my $frameworkcode = &GetFrameworkCode($biblionumber);
426 # Defining which userflag is needing according to the framework currently used
428 if (defined $input->param('frameworkcode')) {
429 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
432 if (not defined $userflags) {
433 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
436 my ($template, $loggedinuser, $cookie)
437 = get_template_and_user({template_name => "cataloguing/additem.tt",
440 flagsrequired => {editcatalogue => $userflags},
445 # Does the user have a restricted item editing permission?
446 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
447 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
448 # In case user is a superlibrarian, editing is not restricted
449 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
450 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
451 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
453 my $tagslib = &GetMarcStructure(1,$frameworkcode);
454 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
456 output_and_exit_if_error( $input, $cookie, $template,
457 { module => 'cataloguing', record => $record } );
459 my $oldrecord = TransformMarcToKoha($record);
461 my $nextop="additem";
462 my @errors; # store errors found while checking data BEFORE saving item.
464 # Getting last created item cookie
465 my $prefillitem = C4::Context->preference('PrefillItem');
467 my $cookieitemrecord;
469 my $lastitemcookie = $input->cookie('LastCreatedItem');
470 if ($lastitemcookie) {
471 $lastitemcookie = decode_base64url($lastitemcookie);
473 if ( thaw($lastitemcookie) ) {
474 $cookieitemrecord = thaw($lastitemcookie);
475 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
479 $lastitemcookie = 'undef' unless $lastitemcookie;
480 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '".encode_base64url($lastitemcookie)."'. Caught error follows: '$@'";
485 #-------------------------------------------------------------------------------
486 if ($op eq "additem") {
488 #-------------------------------------------------------------------------------
490 my @tags = $input->multi_param('tag');
491 my @subfields = $input->multi_param('subfield');
492 my @values = $input->multi_param('field_value');
493 # build indicator hash.
494 my @ind_tag = $input->multi_param('ind_tag');
495 my @indicator = $input->multi_param('indicator');
496 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
497 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
500 my $add_submit = $input->param('add_submit');
501 my $add_duplicate_submit = $input->param('add_duplicate_submit');
502 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
503 my $number_of_copies = $input->param('number_of_copies');
505 # This is a bit tricky : if there is a cookie for the last created item and
506 # we just added an item, the cookie value is not correct yet (it will be updated
507 # next page). To prevent the form from being filled with outdated values, we
508 # force the use of "add and duplicate" feature, so the form will be filled with
510 $add_duplicate_submit = 1 if ($prefillitem);
513 # if autoBarcode is set to 'incremental', calculate barcode...
514 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
515 $record = _increment_barcode($record, $frameworkcode);
518 my $addedolditem = TransformMarcToKoha( $record );
520 # If we have to add or add & duplicate, we add the item
521 if ( $add_submit || $add_duplicate_submit ) {
523 # check for item barcode # being unique
524 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
525 push @errors, "barcode_not_unique" if ($exist_itemnumber);
527 # if barcode exists, don't create, but report The problem.
528 unless ($exist_itemnumber) {
529 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
530 set_item_default_location($oldbibitemnum);
532 # Pushing the last created item cookie back
533 if ($prefillitem && defined $record) {
534 my $itemcookie = $input->cookie(
535 -name => 'LastCreatedItem',
536 # We encode_base64url the whole freezed structure so we're sure we won't have any encoding problems
537 -value => encode_base64url( freeze( $record ) ),
542 $cookie = [ $cookie, $itemcookie ];
547 if ($exist_itemnumber) {
548 $itemrecord = $record;
552 # If we have to add & duplicate
553 if ($add_duplicate_submit) {
554 $itemrecord = $record;
555 if (C4::Context->preference('autoBarcode') eq 'incremental') {
556 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
559 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
560 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
561 my $fieldItem = $itemrecord->field($tagfield);
562 $itemrecord->delete_field($fieldItem);
563 $fieldItem->delete_subfields($tagsubfield);
564 $itemrecord->insert_fields_ordered($fieldItem);
566 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
569 # If we have to add multiple copies
570 if ($add_multiple_copies_submit) {
573 my $barcodeobj = C4::Barcodes->new;
574 my $copynumber = $addedolditem->{'copynumber'};
575 my $oldbarcode = $addedolditem->{'barcode'};
576 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
577 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
579 # If there is a barcode and we can't find their new values, we can't add multiple copies
581 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
582 if ($oldbarcode && !$testbarcode) {
584 push @errors, "no_next_barcode";
585 $itemrecord = $record;
590 # For the first iteration
591 my $barcodevalue = $oldbarcode;
592 my $exist_itemnumber;
595 for (my $i = 0; $i < $number_of_copies;) {
597 # If there is a barcode
600 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
601 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
603 # Putting it into the record
605 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
606 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
607 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
608 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
609 # But when adding multiple copies we need to prefix it here,
610 # so we retrieve the homebranch from the item and prefix the barcode with it.
611 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
612 my $homebranch = $record->subfield($hb_field, $hb_subfield);
613 $barcodevalue = $homebranch . $barcodevalue;
615 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
618 # Checking if the barcode already exists
619 $exist_itemnumber = get_item_from_barcode($barcodevalue);
621 # Updating record with the new copynumber
623 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
627 if (!$exist_itemnumber) {
628 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
629 AddItemFromMarc( $record, $biblionumber, { skip_record_index => 1 } );
630 set_item_default_location($oldbibitemnum);
632 # We count the item only if it was really added
633 # That way, all items are added, even if there was some already existing barcodes
634 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
636 # Only increment copynumber if item was really added
637 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
640 # Preparing the next iteration
641 $oldbarcode = $barcodevalue;
644 my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
645 $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
650 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
651 print $input->redirect(
652 '/cgi-bin/koha/circ/circulation.pl?'
653 .'borrowernumber='.$fa_circborrowernumber
654 .'&barcode='.uri_escape_utf8($fa_barcode)
655 .'&duedatespec='.$fa_duedatespec
662 #-------------------------------------------------------------------------------
663 } elsif ($op eq "edititem") {
664 #-------------------------------------------------------------------------------
665 # retrieve item if exist => then, it's a modif
666 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
667 $nextop = "saveitem";
668 #-------------------------------------------------------------------------------
669 } elsif ($op eq "dupeitem") {
670 #-------------------------------------------------------------------------------
671 # retrieve item if exist => then, it's a modif
672 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
673 if (C4::Context->preference('autoBarcode') eq 'incremental') {
674 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
677 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
678 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
679 my $fieldItem = $itemrecord->field($tagfield);
680 $itemrecord->delete_field($fieldItem);
681 $fieldItem->delete_subfields($tagsubfield);
682 $itemrecord->insert_fields_ordered($fieldItem);
685 #check for hidden subfield and remove them for the duplicated item
686 foreach my $field ($itemrecord->fields()){
687 my $tag = $field->{_tag};
688 foreach my $subfield ($field->subfields()){
689 my $subfieldtag = $subfield->[0];
690 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
691 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
692 my $fieldItem = $itemrecord->field($tag);
693 $itemrecord->delete_field($fieldItem);
694 $fieldItem->delete_subfields($subfieldtag);
695 $itemrecord->insert_fields_ordered($fieldItem);
700 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
702 #-------------------------------------------------------------------------------
703 } elsif ($op eq "delitem") {
704 #-------------------------------------------------------------------------------
705 # check that there is no issue on this item before deletion.
706 my $item = Koha::Items->find($itemnumber);
707 $error = $item->safe_delete;
708 if(ref($error) eq 'Koha::Item'){
709 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
714 #-------------------------------------------------------------------------------
715 } elsif ($op eq "delallitems") {
716 #-------------------------------------------------------------------------------
717 my $items = Koha::Items->search({ biblionumber => $biblionumber });
718 while ( my $item = $items->next ) {
719 $error = $item->safe_delete({ skip_record_index => 1 });
720 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
723 my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
724 $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
728 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
729 my $views = { C4::Search::enabled_staff_search_views };
730 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
731 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
732 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
733 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
734 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
735 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
737 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
741 #-------------------------------------------------------------------------------
742 } elsif ($op eq "saveitem") {
743 #-------------------------------------------------------------------------------
745 my @tags = $input->multi_param('tag');
746 my @subfields = $input->multi_param('subfield');
747 my @values = $input->multi_param('field_value');
748 # build indicator hash.
749 my @ind_tag = $input->multi_param('ind_tag');
750 my @indicator = $input->multi_param('indicator');
751 # my $itemnumber = $input->param('itemnumber');
752 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
753 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
754 # MARC::Record builded => now, record in DB
755 # warn "R: ".$record->as_formatted;
756 # check that the barcode don't exist already
757 my $addedolditem = TransformMarcToKoha($itemtosave);
758 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
759 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
760 push @errors,"barcode_not_unique";
762 my $item = Koha::Items->find($itemnumber );
763 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
765 my $olditemlost = $item->itemlost;
766 my $newitemlost = $newitem->{itemlost};
767 if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
768 LostItem( $item->itemnumber, 'additem' )
772 } elsif ($op eq "delinkitem"){
774 my $analyticfield = '773';
775 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
776 $analyticfield = '773';
777 } elsif ($marcflavour eq 'UNIMARC') {
778 $analyticfield = '461';
780 foreach my $field ($record->field($analyticfield)){
781 if ($field->subfield('9') eq $hostitemnumber){
782 $record->delete_field($field);
786 my $modbibresult = ModBiblio($record, $biblionumber,'');
789 # update OAI-PMH sets
791 if (C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
792 C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
797 #-------------------------------------------------------------------------------
798 # build screen with existing items. and "new" one
799 #-------------------------------------------------------------------------------
801 # now, build existiing item list
802 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
803 #my @fields = $record->fields();
806 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
808 #---- finds where items.itemnumber is stored
809 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
810 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
811 C4::Biblio::EmbedItemsInMarcBiblio({
812 marc_record => $temp,
813 biblionumber => $biblionumber });
814 my @fields = $temp->fields();
818 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
819 my $analyticfield = '773';
820 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
821 $analyticfield = '773';
822 } elsif ($marcflavour eq 'UNIMARC') {
823 $analyticfield = '461';
825 foreach my $hostfield ($temp->field($analyticfield)){
826 my $hostbiblionumber = $hostfield->subfield('0');
827 if ($hostbiblionumber){
828 my $hostrecord = GetMarcBiblio({
829 biblionumber => $hostbiblionumber,
832 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
833 foreach my $hostitem ($hostrecord->field($itemfield)){
834 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
835 push (@fields, $hostitem);
836 push (@hostitemnumbers, $hostfield->subfield('9'));
844 foreach my $field (@fields) {
845 next if ( $field->tag() < 10 );
847 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
849 # loop through each subfield
851 foreach my $subfield (@subf){
852 my $subfieldcode = $subfield->[0];
853 my $subfieldvalue= $subfield->[1];
855 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
856 && ($field->tag() ne $itemtagfield
857 && $subfieldcode ne $itemtagsubfield));
858 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
859 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
860 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
861 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
862 $subfieldcode, $subfieldvalue, '', $tagslib)
866 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
868 my $userenv = C4::Context->userenv();
869 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
870 $this_row{'nomod'} = 1;
873 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
875 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
876 foreach my $hostitemnumber (@hostitemnumbers) {
877 my $item = Koha::Items->find( $hostitemnumber );
878 if ($this_row{itemnumber} eq $hostitemnumber) {
879 $this_row{hostitemflag} = 1;
880 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
887 push(@big_array, \%this_row);
891 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
892 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
894 # now, construct template !
895 # First, the existing items for display
897 my @header_value_loop;
898 for my $row ( @big_array ) {
901 foreach my $key (sort keys %witness){
904 $item_field->{field} = $row->{$key};
906 $item_field->{field} = '';
910 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
913 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
914 next unless $key eq $subfield;
915 $item_field->{datatype} = 'date';
918 push @item_fields, $item_field;
920 $row_data{item_value} = [ @item_fields ];
921 $row_data{itemnumber} = $row->{itemnumber};
922 #reporting this_row values
923 $row_data{'nomod'} = $row->{'nomod'};
924 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
925 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
926 # $row_data{'countanalytics'} = $row->{'countanalytics'};
927 push(@item_value_loop,\%row_data);
929 foreach my $subfield_code (sort keys(%witness)) {
931 $header_value{header_value} = $witness{$subfield_code};
933 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
934 my $kohafield = $subfieldlib->{kohafield};
935 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
936 $header_value{column_name} = $1;
939 push(@header_value_loop, \%header_value);
942 # now, build the item form for entering a new item
946 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
947 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
948 for my $library ( @$libraries ) {
949 $library->{selected} = 1 if $library->{branchcode} eq $branch
952 my $item = Koha::Items->find($itemnumber);
954 # We generate form, from actuel record
957 foreach my $field ($itemrecord->fields()){
958 my $tag = $field->{_tag};
959 foreach my $subfield ( $field->subfields() ){
961 my $subfieldtag = $subfield->[0];
962 my $value = $subfield->[1];
963 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
965 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
967 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
968 push @fields, "$tag$subfieldtag";
969 push (@loop_data, $subfield_data);
975 # and now we add fields that are empty
977 # Using last created item if it exists
979 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
981 # We generate form, and fill with values if defined
982 foreach my $tag ( keys %{$tagslib}){
983 foreach my $subtag (keys %{$tagslib->{$tag}}){
984 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
985 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
986 next if any { /^$tag$subtag$/ } @fields;
988 my @values = (undef);
989 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
990 for my $value (@values){
991 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
992 push (@loop_data, $subfield_data);
997 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
999 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
1001 biblionumber => $biblionumber,
1002 title => $oldrecord->{title},
1003 author => $oldrecord->{author},
1004 item_loop => \@item_value_loop,
1005 item_header_loop => \@header_value_loop,
1006 item => \@loop_data,
1007 itemnumber => $itemnumber,
1008 barcode => $item ? $item->barcode : undef,
1009 itemtagfield => $itemtagfield,
1010 itemtagsubfield => $itemtagsubfield,
1012 popup => scalar $input->param('popup') ? 1: 0,
1013 C4::Search::enabled_staff_search_views,
1015 $template->{'VARS'}->{'searchid'} = $searchid;
1017 if ($frameworkcode eq 'FA'){
1018 # fast cataloguing datas
1020 'circborrowernumber' => $fa_circborrowernumber,
1021 'barcode' => $fa_barcode,
1022 'branch' => $fa_branch,
1023 'stickyduedate' => $fa_stickyduedate,
1024 'duedatespec' => $fa_duedatespec,
1028 foreach my $error (@errors) {
1029 $template->param($error => 1);
1031 output_html_with_http_headers $input, $cookie, $template->output;