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>.
25 use C4::Auth qw( get_template_and_user haspermission );
26 use C4::Output qw( output_and_exit_if_error output_and_exit output_html_with_http_headers );
28 GetAuthorisedValueDesc
33 IsMarcStructureInternal
38 use C4::Items qw( AddItemFromMarc ModItemFromMarc );
40 use C4::Circulation qw( LostItem );
41 use C4::Koha qw( GetAuthorisedValues );
42 use C4::ClassSource qw( GetClassSources GetClassSource );
44 use C4::Barcodes::ValueBuilder;
45 use Koha::DateUtils qw( dt_from_string );
50 use Koha::SearchEngine::Indexer;
51 use C4::Search qw( enabled_staff_search_views );
52 use Storable qw( freeze thaw );
53 use URI::Escape qw( uri_escape_utf8 );
57 use URI::Escape qw( uri_escape_utf8 );
58 use MIME::Base64 qw( decode_base64url encode_base64url );
59 use List::Util qw( first );
60 use List::MoreUtils qw( any uniq );
62 our $dbh = C4::Context->dbh;
64 sub generate_subfield_form {
65 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $subfields, $i, $restrictededition, $item) = @_;
67 my $frameworkcode = &GetFrameworkCode($biblionumber);
72 my $dbh = C4::Context->dbh;
74 my $index_subfield = int(rand(1000000));
75 if ($subfieldtag eq '@'){
76 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
78 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
81 $subfield_data{tag} = $tag;
82 $subfield_data{subfield} = $subfieldtag;
83 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
84 $subfield_data{mandatory} = $subfieldlib->{mandatory};
85 $subfield_data{important} = $subfieldlib->{important};
86 $subfield_data{repeatable} = $subfieldlib->{repeatable};
87 $subfield_data{maxlength} = $subfieldlib->{maxlength};
88 $subfield_data{display_order} = $subfieldlib->{display_order};
89 $subfield_data{kohafield} = $subfieldlib->{kohafield} || 'items.more_subfields_xml';
91 if ( ! defined( $value ) || $value eq '') {
92 $value = $subfieldlib->{defaultvalue};
94 # get today date & replace <<YYYY>>, <<YY>>, <<MM>>, <<DD>> if provided in the default value
95 my $today_dt = dt_from_string;
96 my $year = $today_dt->strftime('%Y');
97 my $shortyear = $today_dt->strftime('%y');
98 my $month = $today_dt->strftime('%m');
99 my $day = $today_dt->strftime('%d');
100 $value =~ s/<<YYYY>>/$year/g;
101 $value =~ s/<<YY>>/$shortyear/g;
102 $value =~ s/<<MM>>/$month/g;
103 $value =~ s/<<DD>>/$day/g;
104 # And <<USER>> with surname (?)
105 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
106 $value=~s/<<USER>>/$username/g;
110 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
112 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
113 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
114 foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
115 my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
116 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
117 $CNsubfields = undef if $CNsubfields eq '';
118 my $temp2 = $temp->field($CNtag);
121 $value = $temp2->as_string( $CNsubfields, ' ' );
126 my $default_location = C4::Context->preference('NewItemsDefaultLocation');
127 if ( !$value && $subfieldlib->{kohafield} eq 'items.location' && $default_location ) {
128 $value = $default_location;
131 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
132 my $input = CGI->new;
133 $value = $input->param('barcode');
136 if ( $subfieldlib->{authorised_value} ) {
137 my @authorised_values;
139 # builds list, depending on authorised value...
140 if ( $subfieldlib->{authorised_value} eq "LOST" ) {
141 my $ClaimReturnedLostValue = C4::Context->preference('ClaimReturnedLostValue');
142 my $item_is_return_claim = $ClaimReturnedLostValue && exists $item->{itemlost} && $ClaimReturnedLostValue eq $item->{itemlost};
143 $subfield_data{IS_RETURN_CLAIM} = $item_is_return_claim;
145 $subfield_data{IS_LOST_AV} = 1;
147 push @authorised_values, qq{};
148 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
150 push @authorised_values, $r->{authorised_value};
151 $authorised_lib{$r->{authorised_value}} = $r->{lib};
154 elsif ( $subfieldlib->{authorised_value} eq "branches" ) {
155 foreach my $thisbranch (@$branches) {
156 push @authorised_values, $thisbranch->{branchcode};
157 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
158 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
161 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
162 push @authorised_values, "";
163 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
166 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
168 $itemtypes = Koha::ItemTypes->search_with_localization;
170 while ( my $itemtype = $itemtypes->next ) {
171 push @authorised_values, $itemtype->itemtype;
172 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
176 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
177 $itype_sth->execute( $biblionumber );
178 ( $value ) = $itype_sth->fetchrow_array;
183 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
184 push @authorised_values, "";
186 my $class_sources = GetClassSources();
187 my $default_source = C4::Context->preference("DefaultClassificationSource");
189 foreach my $class_source (sort keys %$class_sources) {
190 next unless $class_sources->{$class_source}->{'used'} or
191 ($value and $class_source eq $value) or
192 ($class_source eq $default_source);
193 push @authorised_values, $class_source;
194 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
196 $value = $default_source unless ($value);
198 #---- "true" authorised value
201 push @authorised_values, qq{};
202 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
204 push @authorised_values, $r->{authorised_value};
205 $authorised_lib{$r->{authorised_value}} = $r->{lib};
209 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
210 $subfield_data{marc_value} = {
212 id => $subfield_data{id},
213 maxlength => $subfield_data{maxlength},
215 ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
219 $subfield_data{marc_value} = {
221 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
222 values => \@authorised_values,
223 labels => \%authorised_lib,
225 ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
229 # it's a thesaurus / authority field
230 elsif ( $subfieldlib->{authtypecode} ) {
231 $subfield_data{marc_value} = {
233 id => $subfield_data{id},
234 maxlength => $subfield_data{maxlength},
236 authtypecode => $subfieldlib->{authtypecode},
239 # it's a plugin field
240 elsif ( $subfieldlib->{value_builder} ) { # plugin
241 require Koha::FrameworkPlugin;
242 my $plugin = Koha::FrameworkPlugin->new({
243 name => $subfieldlib->{'value_builder'},
246 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
247 id => $subfield_data{id}, tabloop => $subfields };
248 $plugin->build( $pars );
249 if( !$plugin->errstr ) {
250 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
251 $subfield_data{marc_value} = {
252 type => 'text_plugin',
253 id => $subfield_data{id},
254 maxlength => $subfield_data{maxlength},
257 nopopup => $plugin->noclick,
258 javascript => $plugin->javascript,
261 warn $plugin->errstr;
262 $subfield_data{marc_value} = {
264 id => $subfield_data{id},
265 maxlength => $subfield_data{maxlength},
267 }; # supply default input form
270 elsif ( $tag eq '' ) { # it's an hidden field
271 $subfield_data{marc_value} = {
273 id => $subfield_data{id},
274 maxlength => $subfield_data{maxlength},
278 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
279 $subfield_data{marc_value} = {
281 id => $subfield_data{id},
282 maxlength => $subfield_data{maxlength},
288 $value and length($value) > 100
291 C4::Context->preference("marcflavour") eq "UNIMARC"
292 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
295 C4::Context->preference("marcflavour") eq "MARC21"
296 and 500 <= $tag && $tag < 600
299 # oversize field (textarea)
300 $subfield_data{marc_value} = {
302 id => $subfield_data{id},
306 # it's a standard field
307 $subfield_data{marc_value} = {
309 id => $subfield_data{id},
310 maxlength => $subfield_data{maxlength},
315 # Getting list of subfields to keep when restricted editing is enabled
316 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
317 my $allowAllSubfields = (
318 not defined $subfieldsToAllowForRestrictedEditing
319 or $subfieldsToAllowForRestrictedEditing eq q||
321 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
323 # If we're on restricted editing, and our field is not in the list of subfields to allow,
324 # then it is read-only
325 $subfield_data{marc_value}->{readonly} = (
326 not $allowAllSubfields
327 and $restrictededition
328 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
331 return \%subfield_data;
334 sub get_item_from_cookie {
337 my $item_from_cookie;
338 my $lastitemcookie = $input->cookie('LastCreatedItem');
339 if ($lastitemcookie) {
340 $lastitemcookie = decode_base64url($lastitemcookie);
342 if ( thaw($lastitemcookie) ) {
343 $item_from_cookie = thaw($lastitemcookie);
347 $lastitemcookie ||= 'undef';
348 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '".encode_base64url($lastitemcookie)."'. Caught error follows: '$@'";
351 return $item_from_cookie;
354 my $input = CGI->new;
355 my $error = $input->param('error');
359 if( $input->param('itemnumber') && !$input->param('biblionumber') ){
360 $itemnumber = $input->param('itemnumber');
361 my $item = Koha::Items->find( $itemnumber );
362 $biblionumber = $item->biblionumber;
364 $biblionumber = $input->param('biblionumber');
365 $itemnumber = $input->param('itemnumber');
368 my $biblio = Koha::Biblios->find($biblionumber);
370 my $op = $input->param('op') || q{};
371 my $hostitemnumber = $input->param('hostitemnumber');
372 my $marcflavour = C4::Context->preference("marcflavour");
373 my $searchid = $input->param('searchid');
374 # fast cataloguing datas
375 my $fa_circborrowernumber = $input->param('circborrowernumber');
376 my $fa_barcode = $input->param('barcode');
377 my $fa_branch = $input->param('branch');
378 my $fa_stickyduedate = $input->param('stickyduedate');
379 my $fa_duedatespec = $input->param('duedatespec');
381 our $frameworkcode = &GetFrameworkCode($biblionumber);
383 # Defining which userflag is needing according to the framework currently used
385 if (defined $input->param('frameworkcode')) {
386 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
389 if (not defined $userflags) {
390 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
393 my ($template, $loggedinuser, $cookie)
394 = get_template_and_user({template_name => "cataloguing/additem.tt",
397 flagsrequired => {editcatalogue => $userflags},
401 # Does the user have a restricted item editing permission?
402 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
403 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
404 # In case user is a superlibrarian, editing is not restricted
405 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
406 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
407 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
409 our $tagslib = &GetMarcStructure(1,$frameworkcode);
410 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
412 output_and_exit_if_error( $input, $cookie, $template,
413 { module => 'cataloguing', record => $record } );
415 my $oldrecord = TransformMarcToKoha($record);
417 my $nextop="additem";
418 my @errors; # store errors found while checking data BEFORE saving item.
420 # Getting last created item cookie
421 my $prefillitem = C4::Context->preference('PrefillItem');
423 #-------------------------------------------------------------------------------
424 if ($op eq "additem") {
426 my $add_submit = $input->param('add_submit');
427 my $add_duplicate_submit = $input->param('add_duplicate_submit');
428 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
429 my $number_of_copies = $input->param('number_of_copies');
431 my @columns = Koha::Items->columns;
432 my $item = Koha::Item->new;
433 $item->biblionumber($biblio->biblionumber);
434 for my $c ( @columns ) {
435 if ( $c eq 'more_subfields_xml' ) {
436 my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
437 my @unlinked_item_subfields;
438 for my $subfield ( @more_subfields_xml ) {
439 my $v = $input->param('items.more_subfields_xml_' . $subfield);
440 push @unlinked_item_subfields, $subfield, $v;
442 if ( @unlinked_item_subfields ) {
443 my $marc = MARC::Record->new();
444 # use of tag 999 is arbitrary, and doesn't need to match the item tag
445 # used in the framework
446 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
447 $marc->encoding("UTF-8");
448 $item->more_subfields_xml($marc->as_xml("USMARC"));
451 $item->more_subfields_xml(undef);
453 my @v = grep { $_ ne "" }
454 uniq $input->multi_param( "items." . $c );
457 && $c ne 'permanent_location'; # See 27837
459 $item->$c(join ' | ', @v);
463 # if autoBarcode is set to 'incremental', calculate barcode...
464 if ( ! defined $item->barcode && C4::Context->preference('autoBarcode') eq 'incremental' ) {
465 my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
466 $item->barcode($barcode);
469 # If we have to add or add & duplicate, we add the item
470 if ( $add_submit || $prefillitem) {
472 # check for item barcode # being unique
473 if ( defined $item->barcode
474 && Koha::Items->search( { barcode => $item->barcode } )->count )
476 # if barcode exists, don't create, but report The problem.
477 push @errors, "barcode_not_unique";
479 $current_item = $item->unblessed; # Restore edit form for the same item
482 $item->store->discard_changes;
484 # This is a bit tricky : if there is a cookie for the last created item and
485 # we just added an item, the cookie value is not correct yet (it will be updated
486 # next page). To prevent the form from being filled with outdated values, we
487 # force the use of "add and duplicate" feature, so the form will be filled with
490 # Pushing the last created item cookie back
491 if ( $prefillitem ) {
492 my $last_created_item_cookie = $input->cookie(
493 -name => 'LastCreatedItem',
494 # We encode_base64url the whole freezed structure so we're sure we won't have any encoding problems
495 -value => encode_base64url( freeze( { %{$item->unblessed}, itemnumber => undef } ) ),
500 $cookie = [ $cookie, $last_created_item_cookie ];
508 # If we have to add & duplicate
509 if ($prefillitem || $add_duplicate_submit) {
511 $current_item = $item->unblessed;
513 if (C4::Context->preference('autoBarcode') eq 'incremental') {
514 my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
515 $current_item->{barcode} = $barcode;
518 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
519 $current_item->{barcode} = undef; # FIXME or delete?
522 # Don't use the "prefill" feature if we want to generate the form with all the info from this item
523 # It will remove subfields that are not in SubfieldsToUseWhenPrefill.
524 $prefillitem = 0 if $add_duplicate_submit;
527 # If we have to add multiple copies
528 if ($add_multiple_copies_submit) {
530 $current_item = $item->unblessed;
532 my $copynumber = $current_item->{copynumber};
533 my $oldbarcode = $current_item->{barcode};
535 # If there is a barcode and we can't find their new values, we can't add multiple copies
537 my $barcodeobj = C4::Barcodes->new;
538 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
539 if ( $oldbarcode && !$testbarcode ) {
541 push @errors, "no_next_barcode";
547 # For the first iteration
548 my $barcodevalue = $oldbarcode;
549 my $exist_itemnumber;
551 for ( my $i = 0 ; $i < $number_of_copies ; ) {
553 # If there is a barcode
556 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
557 $barcodevalue = $barcodeobj->next_value($oldbarcode)
558 if ( $i > 0 || $exist_itemnumber );
560 # Putting it into the record
562 if ( C4::Context->preference("autoBarcode") eq
563 'hbyymmincr' && $i > 0 )
564 { # The first copy already contains the homebranch prefix
565 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
566 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
567 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
568 # But when adding multiple copies we need to prefix it here,
569 # so we retrieve the homebranch from the item and prefix the barcode with it.
570 my $homebranch = $current_item->{homebranch};
571 $barcodevalue = $homebranch . $barcodevalue;
573 $current_item->{barcode} = $barcodevalue;
576 # Checking if the barcode already exists
577 $exist_itemnumber = Koha::Items->search({ barcode => $barcodevalue })->count;
580 # Updating record with the new copynumber
582 $current_item->{copynumber} = $copynumber;
586 if ( !$exist_itemnumber ) {
587 delete $current_item->{itemnumber};
588 $current_item = Koha::Item->new($current_item)->store(
589 { skip_record_index => 1 } );
590 $current_item->discard_changes; # Cannot chain discard_changes
591 $current_item = $current_item->unblessed;
593 # We count the item only if it was really added
594 # That way, all items are added, even if there was some already existing barcodes
595 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
598 # Only increment copynumber if item was really added
599 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
602 # Preparing the next iteration
603 $oldbarcode = $barcodevalue;
606 my $indexer = Koha::SearchEngine::Indexer->new(
607 { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
608 $indexer->index_records( $biblionumber, "specialUpdate",
611 undef($current_item);
614 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
615 print $input->redirect(
616 '/cgi-bin/koha/circ/circulation.pl?'
617 .'borrowernumber='.$fa_circborrowernumber
618 .'&barcode='.uri_escape_utf8($fa_barcode)
619 .'&duedatespec='.$fa_duedatespec
620 .'&stickyduedate='.$fa_stickyduedate
626 #-------------------------------------------------------------------------------
627 } elsif ($op eq "edititem") {
628 #-------------------------------------------------------------------------------
629 # retrieve item if exist => then, it's a modif
630 $current_item = Koha::Items->find($itemnumber)->unblessed;
631 # FIXME Handle non existent item
632 $nextop = "saveitem";
633 #-------------------------------------------------------------------------------
634 } elsif ($op eq "dupeitem") {
635 #-------------------------------------------------------------------------------
636 # retrieve item if exist => then, it's a modif
637 my $item = Koha::Items->find($itemnumber);
638 # FIXME Handle non existent item
639 if (C4::Context->preference('autoBarcode') eq 'incremental') {
640 my ( $barcode ) = C4::Barcodes::ValueBuilder::incremental::get_barcode;
641 $item->barcode($barcode);
644 $item->barcode(undef); # Don't save it!
648 #-------------------------------------------------------------------------------
649 } elsif ($op eq "delitem") {
650 #-------------------------------------------------------------------------------
651 # check that there is no issue on this item before deletion.
652 my $item = Koha::Items->find($itemnumber);
653 $error = $item->safe_delete;
654 if(ref($error) eq 'Koha::Item'){
655 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
660 #-------------------------------------------------------------------------------
661 } elsif ($op eq "delallitems") {
662 #-------------------------------------------------------------------------------
663 my $items = Koha::Items->search({ biblionumber => $biblionumber });
664 while ( my $item = $items->next ) {
665 $error = $item->safe_delete({ skip_record_index => 1 });
666 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
669 my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
670 $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
674 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
675 my $views = { C4::Search::enabled_staff_search_views };
676 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
677 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
678 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
679 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
680 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
681 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
683 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
687 #-------------------------------------------------------------------------------
688 } elsif ($op eq "saveitem") {
689 #-------------------------------------------------------------------------------
691 my $itemnumber = $input->param('itemnumber');
692 my $item = Koha::Items->find($itemnumber);
693 # FIXME Handle non existent item
694 my $olditemlost = $item->itemlost;
695 my @columns = Koha::Items->columns;
696 for my $c ( @columns ) {
697 if ( $c eq 'more_subfields_xml' ) {
698 my @more_subfields_xml = $input->multi_param("items.more_subfields_xml");
699 my @unlinked_item_subfields;
700 for my $subfield ( uniq @more_subfields_xml ) {
701 my @v = $input->multi_param('items.more_subfields_xml_' . $subfield);
702 push @unlinked_item_subfields, $subfield, $_ for @v;
704 if ( @unlinked_item_subfields ) {
705 my $marc = MARC::Record->new();
706 # use of tag 999 is arbitrary, and doesn't need to match the item tag
707 # used in the framework
708 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @unlinked_item_subfields));
709 $marc->encoding("UTF-8");
710 $item->more_subfields_xml($marc->as_xml("USMARC"));
713 $item->more_subfields_xml(undef);
715 my @v = $input->multi_param("items.".$c);
717 $item->$c(join ' | ', uniq @v);
721 # check that the barcode don't exist already
723 defined $item->barcode
724 && Koha::Items->search(
726 barcode => $item->barcode,
727 itemnumber => { '!=' => $item->itemnumber }
732 # FIXME We shouldn't need that, ->store would explode as there is a unique constraint on items.barcode
733 push @errors,"barcode_not_unique";
734 $current_item = $item->unblessed; # Restore edit form for the same item
736 my $newitemlost = $item->itemlost;
737 if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
738 LostItem( $item->itemnumber, 'additem' );
744 } elsif ($op eq "delinkitem"){
746 my $analyticfield = '773';
747 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
748 $analyticfield = '773';
749 } elsif ($marcflavour eq 'UNIMARC') {
750 $analyticfield = '461';
752 foreach my $field ($record->field($analyticfield)){
753 if ($field->subfield('9') eq $hostitemnumber){
754 $record->delete_field($field);
758 my $modbibresult = ModBiblio($record, $biblionumber,'');
761 # update OAI-PMH sets
763 if (C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
764 C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
769 #-------------------------------------------------------------------------------
770 # build screen with existing items. and "new" one
771 #-------------------------------------------------------------------------------
773 # now, build existiing item list
776 for my $item ( $biblio->items->as_list, $biblio->host_items->as_list ) {
777 push @items, $item->columns_to_str;
780 my @witness_attributes = uniq map {
782 map { defined $item->{$_} && $item->{$_} ne "" ? $_ : () } keys %$item
785 our ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField("items.itemnumber");
787 my $subfieldcode_attribute_mappings;
788 for my $subfield_code ( keys %{ $tagslib->{$itemtagfield} } ) {
790 my $subfield = $tagslib->{$itemtagfield}->{$subfield_code};
792 next if IsMarcStructureInternal( $subfield );
793 next unless $subfield->{tab} eq 10; # Is this really needed?
796 if ( $subfield->{kohafield} ) {
797 ( $attribute = $subfield->{kohafield} ) =~ s|^items\.||;
799 $attribute = $subfield_code; # It's in more_subfields_xml
801 next unless grep { $attribute eq $_ } @witness_attributes;
802 $subfieldcode_attribute_mappings->{$subfield_code} = $attribute;
805 my @header_value_loop = map {
807 header_value => $tagslib->{$itemtagfield}->{$_}->{lib},
808 attribute => $subfieldcode_attribute_mappings->{$_},
811 } sort keys %$subfieldcode_attribute_mappings;
813 # now, build the item form for entering a new item
814 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
815 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
816 for my $library ( @$libraries ) {
817 $library->{selected} = 1 if $library->{branchcode} eq $branch
821 # Using last created item if it exists
824 && $op ne "edititem" )
826 my $item_from_cookie = get_item_from_cookie($input);
827 $current_item = $item_from_cookie if $item_from_cookie;
830 my @subfields_to_prefill = split ' ', C4::Context->preference('SubfieldsToUseWhenPrefill');
832 if ( $current_item->{more_subfields_xml} ) {
833 $current_item->{marc_more_subfields_xml} = MARC::Record->new_from_xml($current_item->{more_subfields_xml}, 'UTF-8');
836 # We generate form, and fill with values if defined
837 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
840 foreach my $tag ( keys %{$tagslib} ) {
841 foreach my $subtag ( keys %{ $tagslib->{$tag} } ) {
843 my $subfield = $tagslib->{$tag}{$subtag};
845 next if IsMarcStructureInternal( $subfield );
846 next if ( $subfield->{tab} ne "10" );
852 # If we are not adding a new item
854 # If the subfield must be prefilled with last catalogued item
859 || ( $prefillitem && grep { $_ eq $subtag }
860 @subfields_to_prefill )
864 my $kohafield = $subfield->{kohafield};
867 # This is a mapped field
868 ( my $attribute = $kohafield ) =~ s|^items\.||;
869 push @values, $subfield->{repeatable}
870 ? split '\s\|\s', $current_item->{$attribute}
871 : $current_item->{$attribute}
872 if defined $current_item->{$attribute};
874 # Not mapped, picked the values from more_subfields_xml's MARC
875 my $marc_more = $current_item->{marc_more_subfields_xml};
877 for my $f ( $marc_more->fields($tag) ) {
878 push @values, $f->subfield($subtag);
884 @values = ('') unless @values;
886 for my $value (@values) {
887 my $subfield_data = generate_subfield_form(
890 $subfield, $libraries,
891 $biblionumber, $temp,
893 $restrictededition, $current_item,
895 push @subfields, $subfield_data;
900 @subfields = sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} } @subfields;
902 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
904 biblionumber => $biblionumber,
905 title => $oldrecord->{title},
906 author => $oldrecord->{author},
908 item_header_loop => \@header_value_loop,
909 subfields => \@subfields,
910 itemnumber => $itemnumber,
911 barcode => $current_item->{barcode},
912 itemtagfield => $itemtagfield,
913 itemtagsubfield => $itemtagsubfield,
915 popup => scalar $input->param('popup') ? 1: 0,
916 C4::Search::enabled_staff_search_views,
918 $template->{'VARS'}->{'searchid'} = $searchid;
920 if ($frameworkcode eq 'FA'){
921 # fast cataloguing datas
923 'circborrowernumber' => $fa_circborrowernumber,
924 'barcode' => $fa_barcode,
925 'branch' => $fa_branch,
926 'stickyduedate' => $fa_stickyduedate,
927 'duedatespec' => $fa_duedatespec,
931 foreach my $error (@errors) {
932 $template->param($error => 1);
934 output_html_with_http_headers $input, $cookie, $template->output;