3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Copyright 2011 Equinox Software, Inc.
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>.
24 use vars qw(@ISA @EXPORT_OK);
45 GetAuthorisedValueDesc
47 GetMarcSubfieldStructure
48 IsMarcStructureInternal
50 GetMarcSubfieldStructureFromKohaField
57 EmbedItemsInMarcBiblio
62 LinkBibHeadingsToAuthorities
68 TransformMarcToKohaOneField
72 # those functions are exported but should not be used
73 # they are useful in a few circumstances, so they are exported,
74 # but don't use them unless you are a core developer ;-)
81 use Try::Tiny qw( catch try );
84 use List::MoreUtils qw( uniq );
86 use MARC::File::USMARC;
88 use POSIX qw( strftime );
89 use Module::Load::Conditional qw( can_load );
92 use C4::Log qw( logaction ); # logaction
94 use C4::ClassSource qw( GetClassSort GetClassSource );
103 use C4::Items qw( GetHiddenItemnumbers GetMarcItem );
107 use Koha::Authority::Types;
108 use Koha::Acquisition::Currencies;
109 use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
110 use Koha::Biblio::Metadatas;
113 use Koha::MarcOverlayRules;
115 use Koha::SearchEngine;
116 use Koha::SearchEngine::Indexer;
118 use Koha::Util::MARC;
122 C4::Biblio - cataloging management functions
126 Biblio.pm contains functions for managing storage and editing of bibliographic data within Koha. Most of the functions in this module are used for cataloging records: adding, editing, or removing biblios, biblioitems, or items. Koha's stores bibliographic information in three places:
130 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
132 =item 2. as raw MARC in the Zebra index and storage engine
134 =item 3. as MARC XML in biblio_metadata.metadata
138 In the 3.0 version of Koha, the authoritative record-level information is in biblio_metadata.metadata
140 Because the data isn't completely normalized there's a chance for information to get out of sync. The design choice to go with a un-normalized schema was driven by performance and stability concerns. However, if this occur, it can be considered as a bug : The API is (or should be) complete & the only entry point for all biblio/items managements.
144 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
146 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
150 Because of this design choice, the process of managing storage and editing is a bit convoluted. Historically, Biblio.pm's grown to an unmanagable size and as a result we have several types of functions currently:
154 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
156 =item 2. _koha_* - low-level internal functions for managing the koha tables
158 =item 3. Marc management function : as the MARC record is stored in biblio_metadata.metadata, some subs dedicated to it's management are in this package. They should be used only internally by Biblio.pm, the only official entry points being AddBiblio, AddItem, ModBiblio, ModItem.
160 =item 4. Zebra functions used to update the Zebra index
162 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
166 The MARC record (in biblio_metadata.metadata) contains the complete marc record, including items. It also contains the biblionumber. That is the reason why it is not stored directly by AddBiblio, with all other fields . To save a biblio, we need to :
170 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
172 =item 2. add the biblionumber and biblioitemnumber into the MARC records
174 =item 3. save the marc record
178 =head1 EXPORTED FUNCTIONS
182 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
184 Exported function (core API) for adding a new biblio to koha.
186 The first argument is a C<MARC::Record> object containing the
187 bib to add, while the second argument is the desired MARC
190 This function also accepts a third, optional argument: a hashref
191 to additional options. The only defined option is C<defer_marc_save>,
192 which if present and mapped to a true value, causes C<AddBiblio>
193 to omit the call to save the MARC in C<biblio_metadata.metadata>
194 This option is provided B<only>
195 for the use of scripts such as C<bulkmarcimport.pl> that may need
196 to do some manipulation of the MARC record for item parsing before
197 saving it and which cannot afford the performance hit of saving
198 the MARC record twice. Consequently, do not use that option
199 unless you can guarantee that C<ModBiblioMarc> will be called.
205 my $frameworkcode = shift;
206 my $options = @_ ? shift : undef;
207 my $defer_marc_save = 0;
209 carp('AddBiblio called with undefined record');
212 if ( defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'} ) {
213 $defer_marc_save = 1;
216 my $schema = Koha::Database->schema;
217 my ( $biblionumber, $biblioitemnumber );
219 $schema->txn_do(sub {
221 # transform the data into koha-table style data
222 SetUTF8Flag($record);
223 my $olddata = TransformMarcToKoha( $record, $frameworkcode );
225 my $biblio = Koha::Biblio->new(
227 frameworkcode => $frameworkcode,
228 author => $olddata->{author},
229 title => $olddata->{title},
230 subtitle => $olddata->{subtitle},
231 medium => $olddata->{medium},
232 part_number => $olddata->{part_number},
233 part_name => $olddata->{part_name},
234 unititle => $olddata->{unititle},
235 notes => $olddata->{notes},
237 ( $olddata->{serial} || $olddata->{seriestitle} ? 1 : 0 ),
238 seriestitle => $olddata->{seriestitle},
239 copyrightdate => $olddata->{copyrightdate},
240 datecreated => \'NOW()',
241 abstract => $olddata->{abstract},
244 $biblionumber = $biblio->biblionumber;
245 Koha::Exceptions::ObjectNotCreated->throw unless $biblio;
247 my ($cn_sort) = GetClassSort( $olddata->{'biblioitems.cn_source'}, $olddata->{'cn_class'}, $olddata->{'cn_item'} );
248 my $biblioitem = Koha::Biblioitem->new(
250 biblionumber => $biblionumber,
251 volume => $olddata->{volume},
252 number => $olddata->{number},
253 itemtype => $olddata->{itemtype},
254 isbn => $olddata->{isbn},
255 issn => $olddata->{issn},
256 publicationyear => $olddata->{publicationyear},
257 publishercode => $olddata->{publishercode},
258 volumedate => $olddata->{volumedate},
259 volumedesc => $olddata->{volumedesc},
260 collectiontitle => $olddata->{collectiontitle},
261 collectionissn => $olddata->{collectionissn},
262 collectionvolume => $olddata->{collectionvolume},
263 editionstatement => $olddata->{editionstatement},
264 editionresponsibility => $olddata->{editionresponsibility},
265 illus => $olddata->{illus},
266 pages => $olddata->{pages},
267 notes => $olddata->{bnotes},
268 size => $olddata->{size},
269 place => $olddata->{place},
270 lccn => $olddata->{lccn},
271 url => $olddata->{url},
272 cn_source => $olddata->{'biblioitems.cn_source'},
273 cn_class => $olddata->{cn_class},
274 cn_item => $olddata->{cn_item},
275 cn_suffix => $olddata->{cn_suff},
277 totalissues => $olddata->{totalissues},
278 ean => $olddata->{ean},
279 agerestriction => $olddata->{agerestriction},
282 Koha::Exceptions::ObjectNotCreated->throw unless $biblioitem;
283 $biblioitemnumber = $biblioitem->biblioitemnumber;
285 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
287 # update MARC subfield that stores biblioitems.cn_sort
288 _koha_marc_update_biblioitem_cn_sort( $record, $olddata, $frameworkcode );
290 if (C4::Context->preference('BiblioAddsAuthorities')) {
291 BiblioAutoLink( $record, $frameworkcode );
295 ModBiblioMarc( $record, $biblionumber ) unless $defer_marc_save;
297 # update OAI-PMH sets
298 if(C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
299 C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
302 _after_biblio_action_hooks({ action => 'create', biblio_id => $biblionumber });
304 logaction( "CATALOGUING", "ADD", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
308 ( $biblionumber, $biblioitemnumber ) = ( undef, undef );
310 return ( $biblionumber, $biblioitemnumber );
315 ModBiblio($record, $biblionumber, $frameworkcode, $options);
317 Replace an existing bib record identified by C<$biblionumber>
318 with one supplied by the MARC::Record object C<$record>. The embedded
319 item, biblioitem, and biblionumber fields from the previous
320 version of the bib record replace any such fields of those tags that
321 are present in C<$record>. Consequently, ModBiblio() is not
322 to be used to try to modify item records.
324 C<$frameworkcode> specifies the MARC framework to use
325 when storing the modified bib record; among other things,
326 this controls how MARC fields get mapped to display columns
327 in the C<biblio> and C<biblioitems> tables, as well as
328 which fields are used to store embedded item, biblioitem,
329 and biblionumber data for indexing.
331 The C<$options> argument is a hashref with additional parameters:
335 =item C<overlay_context>
337 This parameter is forwarded to L</ApplyMarcOverlayRules> where it is used for
338 selecting the current rule set if MARCOverlayRules is enabled.
339 See L</ApplyMarcOverlayRules> for more details.
341 =item C<disable_autolink>
343 Unless C<disable_autolink> is passed ModBiblio will relink record headings
344 to authorities based on settings in the system preferences. This flag allows
345 us to not relink records when the authority linker is saving modifications.
347 =item C<skip_holds_queue>
349 Unless C<skip_holds_queue> is passed, ModBiblio will trigger the BatchUpdateBiblioHoldsQueue
350 task to rebuild the holds queue for the biblio.
354 Returns 1 on success 0 on failure
359 my ( $record, $biblionumber, $frameworkcode, $options ) = @_;
363 carp 'No record passed to ModBiblio';
367 if ( C4::Context->preference("CataloguingLog") ) {
368 my $newrecord = GetMarcBiblio({ biblionumber => $biblionumber });
369 logaction( "CATALOGUING", "MODIFY", $biblionumber, "biblio BEFORE=>" . $newrecord->as_formatted );
372 if ( !$options->{disable_autolink} && C4::Context->preference('BiblioAddsAuthorities') ) {
373 BiblioAutoLink( $record, $frameworkcode );
376 # Cleaning up invalid fields must be done early or SetUTF8Flag is liable to
377 # throw an exception which probably won't be handled.
378 foreach my $field ($record->fields()) {
379 if (! $field->is_control_field()) {
380 if (scalar($field->subfields()) == 0 || (scalar($field->subfields()) == 1 && $field->subfield('9'))) {
381 $record->delete_field($field);
386 SetUTF8Flag($record);
387 my $dbh = C4::Context->dbh;
389 $frameworkcode = "" if !$frameworkcode || $frameworkcode eq "Default"; # XXX
391 _strip_item_fields($record, $frameworkcode);
393 # apply overlay rules
394 if ( C4::Context->preference('MARCOverlayRules')
397 && exists $options->{overlay_context} )
399 $record = ApplyMarcOverlayRules(
401 biblionumber => $biblionumber,
403 overlay_context => $options->{overlay_context},
408 # update biblionumber and biblioitemnumber in MARC
409 # FIXME - this is assuming a 1 to 1 relationship between
410 # biblios and biblioitems
411 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
412 $sth->execute($biblionumber);
413 my ($biblioitemnumber) = $sth->fetchrow;
415 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
417 # load the koha-table data object
418 my $oldbiblio = TransformMarcToKoha( $record, $frameworkcode );
420 # update MARC subfield that stores biblioitems.cn_sort
421 _koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode );
423 # update the MARC record (that now contains biblio and items) with the new record data
424 ModBiblioMarc( $record, $biblionumber );
426 # modify the other koha tables
427 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
428 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
430 _after_biblio_action_hooks({ action => 'modify', biblio_id => $biblionumber });
432 # update OAI-PMH sets
433 if(C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
434 C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
437 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
439 biblio_ids => [ $biblionumber ]
441 ) unless $options->{skip_holds_queue};
446 =head2 _strip_item_fields
448 _strip_item_fields($record, $frameworkcode)
450 Utility routine to remove item tags from a
455 sub _strip_item_fields {
457 my $frameworkcode = shift;
458 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
459 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" );
461 # delete any item fields from incoming record to avoid
462 # duplication or incorrect data - use AddItem() or ModItem()
464 foreach my $field ( $record->field($itemtag) ) {
465 $record->delete_field($field);
471 my $error = &DelBiblio($biblionumber);
473 Exported function (core API) for deleting a biblio in koha.
474 Deletes biblio record from Zebra and Koha tables (biblio & biblioitems)
475 Also backs it up to deleted* tables.
476 Checks to make sure that the biblio has no items attached.
478 C<$error> : undef unless an error occurs
483 my ($biblionumber, $params) = @_;
485 my $biblio = Koha::Biblios->find( $biblionumber );
486 return unless $biblio; # Should we throw an exception instead?
488 my $dbh = C4::Context->dbh;
489 my $error; # for error handling
491 # First make sure this biblio has no items attached
492 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
493 $sth->execute($biblionumber);
494 if ( my $itemnumber = $sth->fetchrow ) {
496 # Fix this to use a status the template can understand
497 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
500 return $error if $error;
502 # We delete any existing holds
503 my $holds = $biblio->holds;
504 while ( my $hold = $holds->next ) {
505 # no need to update the holds queue on each step, we'll do it at the end
506 $hold->cancel({ skip_holds_queue => 1 });
509 unless ( $params->{skip_record_index} ){
510 my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
511 $indexer->index_records( $biblionumber, "recordDelete", "biblioserver" );
514 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
515 $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
516 $sth->execute($biblionumber);
517 while ( my $biblioitemnumber = $sth->fetchrow ) {
519 # delete this biblioitem
520 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
521 return $error if $error;
525 # delete biblio from Koha tables and save in deletedbiblio
526 # must do this *after* _koha_delete_biblioitems, otherwise
527 # delete cascade will prevent deletedbiblioitems rows
528 # from being generated by _koha_delete_biblioitems
529 $error = _koha_delete_biblio( $dbh, $biblionumber );
531 _after_biblio_action_hooks({ action => 'delete', biblio_id => $biblionumber });
533 logaction( "CATALOGUING", "DELETE", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
535 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
537 biblio_ids => [ $biblionumber ]
545 =head2 BiblioAutoLink
547 my $headings_linked = BiblioAutoLink($record, $frameworkcode)
549 Automatically links headings in a bib record to authorities.
551 Returns the number of headings changed
557 my $frameworkcode = shift;
560 carp('Undefined record passed to BiblioAutoLink');
563 my ( $num_headings_changed, %results );
566 "C4::Linker::" . ( C4::Context->preference("LinkerModule") || 'Default' );
567 unless ( can_load( modules => { $linker_module => undef } ) ) {
568 $linker_module = 'C4::Linker::Default';
569 unless ( can_load( modules => { $linker_module => undef } ) ) {
574 my $linker = $linker_module->new(
575 { 'options' => C4::Context->preference("LinkerOptions") } );
576 my ( $headings_changed, $results ) =
577 LinkBibHeadingsToAuthorities( $linker, $record, $frameworkcode, C4::Context->preference("CatalogModuleRelink") || '', undef, $verbose );
578 # By default we probably don't want to relink things when cataloging
579 return $headings_changed, $results;
582 =head2 LinkBibHeadingsToAuthorities
584 my $num_headings_changed, %results = LinkBibHeadingsToAuthorities($linker, $marc, $frameworkcode, [$allowrelink, $tagtolink, $verbose]);
586 Links bib headings to authority records by checking
587 each authority-controlled field in the C<MARC::Record>
588 object C<$marc>, looking for a matching authority record,
589 and setting the linking subfield $9 to the ID of that
592 If $allowrelink is false, existing authids will never be
593 replaced, regardless of the values of LinkerKeepStale and
596 Returns the number of heading links changed in the
601 sub LinkBibHeadingsToAuthorities {
604 my $frameworkcode = shift;
605 my $allowrelink = shift;
606 my $tagtolink = shift;
610 carp 'LinkBibHeadingsToAuthorities called on undefined bib record';
614 require C4::AuthoritiesMarc;
616 $allowrelink = 1 unless defined $allowrelink;
617 my $num_headings_changed = 0;
618 foreach my $field ( $bib->fields() ) {
619 if ( defined $tagtolink ) {
620 next unless $field->tag() == $tagtolink ;
622 my $heading = C4::Heading->new_from_field( $field, $frameworkcode );
623 next unless defined $heading;
626 my $current_link = $field->subfield('9');
628 if ( defined $current_link && (!$allowrelink || !C4::Context->preference('LinkerRelink')) )
630 $results{'linked'}->{ $heading->display_form() }++;
631 push(@{$results{'details'}}, { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED'}) if $verbose;
635 my ( $authid, $fuzzy, $match_count ) = $linker->get_link($heading);
637 $results{ $fuzzy ? 'fuzzy' : 'linked' }
638 ->{ $heading->display_form() }++;
639 if(defined $current_link and $current_link == $authid) {
640 push(@{$results{'details'}}, { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED'}) if $verbose;
644 $field->delete_subfield( code => '9' ) if defined $current_link;
645 $field->add_subfields( '9', $authid );
646 $num_headings_changed++;
647 push(@{$results{'details'}}, { tag => $field->tag(), authid => $authid, status => 'LOCAL_FOUND'}) if $verbose;
650 my $authority_type = Koha::Authority::Types->find( $heading->auth_type() );
651 if ( defined $current_link
652 && (!$allowrelink || C4::Context->preference('LinkerKeepStale')) )
654 $results{'fuzzy'}->{ $heading->display_form() }++;
655 push(@{$results{'details'}}, { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED'}) if $verbose;
657 elsif ( C4::Context->preference('AutoCreateAuthorities') ) {
658 if ( _check_valid_auth_link( $current_link, $field ) ) {
659 $results{'linked'}->{ $heading->display_form() }++;
661 elsif ( !$match_count ) {
662 my $authority_type = Koha::Authority::Types->find( $heading->auth_type() );
663 my $marcrecordauth = MARC::Record->new();
664 if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
665 $marcrecordauth->leader(' nz a22 o 4500');
666 SetMarcUnicodeFlag( $marcrecordauth, 'MARC21' );
668 $field->delete_subfield( code => '9' )
669 if defined $current_link;
671 foreach my $subfield ( $field->subfields() ){
672 if ( $subfield->[0] =~ /[A-z]/
673 && C4::Heading::valid_heading_subfield(
674 $field->tag, $subfield->[0] )
676 push @auth_subfields, $subfield->[0] => $subfield->[1];
679 # Bib headings contain some ending punctuation that should NOT
680 # be included in the authority record. Strip those before creation
681 next unless @auth_subfields; # Don't try to create a record if we have no fields;
682 my $last_sub = pop @auth_subfields;
683 $last_sub =~ s/[\s]*[,.:=;!%\/][\s]*$//;
684 push @auth_subfields, $last_sub;
685 my $authfield = MARC::Field->new( $authority_type->auth_tag_to_report, '', '', @auth_subfields );
686 $marcrecordauth->insert_fields_ordered($authfield);
688 # bug 2317: ensure new authority knows it's using UTF-8; currently
689 # only need to do this for MARC21, as MARC::Record->as_xml_record() handles
690 # automatically for UNIMARC (by not transcoding)
691 # FIXME: AddAuthority() instead should simply explicitly require that the MARC::Record
692 # use UTF-8, but as of 2008-08-05, did not want to introduce that kind
693 # of change to a core API just before the 3.0 release.
695 if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
696 my $userenv = C4::Context->userenv;
698 if ( $userenv && $userenv->{'branch'} ) {
699 $library = Koha::Libraries->find( $userenv->{'branch'} );
701 $marcrecordauth->insert_fields_ordered(
704 'a' => "Machine generated authority record."
708 $bib->author() . ", "
709 . $bib->title_proper() . ", "
710 . $bib->publication_date() . " ";
711 $cite =~ s/^[\s\,]*//;
712 $cite =~ s/[\s\,]*$//;
715 . ( $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode') ) . ")"
716 . $bib->subfield( '999', 'c' ) . ": "
718 $marcrecordauth->insert_fields_ordered(
719 MARC::Field->new( '670', '', '', 'a' => $cite ) );
722 # warn "AUTH RECORD ADDED : ".$marcrecordauth->as_formatted;
725 C4::AuthoritiesMarc::AddAuthority( $marcrecordauth, '',
726 $heading->auth_type() );
727 $field->add_subfields( '9', $authid );
728 $num_headings_changed++;
729 $linker->update_cache($heading, $authid);
730 $results{'added'}->{ $heading->display_form() }++;
731 push(@{$results{'details'}}, { tag => $field->tag(), authid => $authid, status => 'CREATED'}) if $verbose;
734 elsif ( defined $current_link ) {
735 if ( _check_valid_auth_link( $current_link, $field ) ) {
736 $results{'linked'}->{ $heading->display_form() }++;
737 push(@{$results{'details'}}, { tag => $field->tag(), authid => $authid, status => 'UNCHANGED'}) if $verbose;
740 $field->delete_subfield( code => '9' );
741 $num_headings_changed++;
742 $results{'unlinked'}->{ $heading->display_form() }++;
743 push(@{$results{'details'}}, { tag => $field->tag(), authid => undef, status => 'NONE_FOUND', auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report}) if $verbose;
747 $results{'unlinked'}->{ $heading->display_form() }++;
748 push(@{$results{'details'}}, { tag => $field->tag(), authid => undef, status => 'NONE_FOUND', auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report}) if $verbose;
753 push(@{$results{'details'}}, { tag => '', authid => undef, status => 'UNCHANGED'}) unless %results;
754 return $num_headings_changed, \%results;
757 =head2 _check_valid_auth_link
759 if ( _check_valid_auth_link($authid, $field) ) {
763 Check whether the specified heading-auth link is valid without reference
764 to Zebra. Ideally this code would be in C4::Heading, but that won't be
765 possible until we have de-cycled C4::AuthoritiesMarc, so this is the
770 sub _check_valid_auth_link {
771 my ( $authid, $field ) = @_;
772 require C4::AuthoritiesMarc;
774 return C4::AuthoritiesMarc::CompareFieldWithAuthority( { 'field' => $field, 'authid' => $authid } );
779 $data = &GetBiblioData($biblionumber);
781 Returns information about the book with the given biblionumber.
782 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
783 the C<biblio> and C<biblioitems> tables in the
786 In addition, C<$data-E<gt>{subject}> is the list of the book's
787 subjects, separated by C<" , "> (space, comma, space).
788 If there are multiple biblioitems with the given biblionumber, only
789 the first one is considered.
795 my $dbh = C4::Context->dbh;
797 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
799 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
800 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
801 WHERE biblio.biblionumber = ?";
803 my $sth = $dbh->prepare($query);
804 $sth->execute($bibnum);
806 $data = $sth->fetchrow_hashref;
810 } # sub GetBiblioData
814 $isbd = &GetISBDView({
815 'record' => $marc_record,
816 'template' => $interface, # opac/intranet
817 'framework' => $framework,
820 Return the ISBD view which can be included in opac and intranet
827 # Expecting record WITH items.
828 my $record = $params->{record};
829 return unless defined $record;
831 my $template = $params->{template} // q{};
832 my $sysprefname = $template eq 'opac' ? 'opacisbd' : 'isbd';
833 my $framework = $params->{framework};
834 my $itemtype = $framework;
835 my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch" );
836 my $tagslib = GetMarcStructure( 1, $itemtype, { unsafe => 1 } );
838 my $ISBD = C4::Context->preference($sysprefname);
843 foreach my $isbdfield ( split( /#/, $bloc ) ) {
845 # $isbdfield= /(.?.?.?)/;
846 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
847 my $fieldvalue = $1 || 0;
848 my $subfvalue = $2 || "";
850 my $analysestring = $4;
853 # warn "==> $1 / $2 / $3 / $4";
854 # my $fieldvalue=substr($isbdfield,0,3);
855 if ( $fieldvalue > 0 ) {
856 my $hasputtextbefore = 0;
857 my @fieldslist = $record->field($fieldvalue);
858 @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf );
860 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
861 # warn "FV : $fieldvalue";
862 if ( $subfvalue ne "" ) {
863 # OPAC hidden subfield
865 if ( ( $template eq 'opac' )
866 && ( $tagslib->{$fieldvalue}->{$subfvalue}->{'hidden'} || 0 ) > 0 );
867 foreach my $field (@fieldslist) {
868 foreach my $subfield ( $field->subfield($subfvalue) ) {
869 my $calculated = $analysestring;
870 my $tag = $field->tag();
873 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib );
874 my $tagsubf = $tag . $subfvalue;
875 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
876 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
878 # field builded, store the result
879 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
880 $blocres .= $textbefore;
881 $hasputtextbefore = 1;
884 # remove punctuation at start
885 $calculated =~ s/^( |;|:|\.|-)*//g;
886 $blocres .= $calculated;
891 $blocres .= $textafter if $hasputtextbefore;
893 foreach my $field (@fieldslist) {
894 my $calculated = $analysestring;
895 my $tag = $field->tag();
898 my @subf = $field->subfields;
899 for my $i ( 0 .. $#subf ) {
900 my $valuecode = $subf[$i][1];
901 my $subfieldcode = $subf[$i][0];
902 # OPAC hidden subfield
904 if ( ( $template eq 'opac' )
905 && ( $tagslib->{$fieldvalue}->{$subfieldcode}->{'hidden'} || 0 ) > 0 );
906 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib );
907 my $tagsubf = $tag . $subfieldcode;
909 $calculated =~ s/ # replace all {{}} codes by the value code.
910 \{\{$tagsubf\}\} # catch the {{actualcode}}
912 $valuecode # replace by the value code
915 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
916 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
919 # field builded, store the result
920 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
921 $blocres .= $textbefore;
922 $hasputtextbefore = 1;
925 # remove punctuation at start
926 $calculated =~ s/^( |;|:|\.|-)*//g;
927 $blocres .= $calculated;
930 $blocres .= $textafter if $hasputtextbefore;
933 $blocres .= $isbdfield;
938 $res =~ s/\{(.*?)\}//g;
940 $res =~ s/\n/<br\/>/g;
948 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
950 =head2 IsMarcStructureInternal
952 my $tagslib = C4::Biblio::GetMarcStructure();
953 for my $tag ( sort keys %$tagslib ) {
955 for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
956 next if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
961 GetMarcStructure creates keys (lib, tab, mandatory, repeatable, important) for a display purpose.
962 These different values should not be processed as valid subfields.
966 sub IsMarcStructureInternal {
967 my ( $subfield ) = @_;
968 return ref $subfield ? 0 : 1;
971 =head2 GetMarcStructure
973 $res = GetMarcStructure($forlibrarian, $frameworkcode, [ $params ]);
975 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
976 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
977 $frameworkcode : the framework code to read
978 $params allows you to pass { unsafe => 1 } for better performance.
980 Note: If you call GetMarcStructure with unsafe => 1, do not modify or
981 even autovivify its contents. It is a cached/shared data structure. Your
982 changes c/would be passed around in subsequent calls.
986 sub GetMarcStructure {
987 my ( $forlibrarian, $frameworkcode, $params ) = @_;
988 $frameworkcode = "" unless $frameworkcode;
990 $forlibrarian = $forlibrarian ? 1 : 0;
991 my $unsafe = ($params && $params->{unsafe})? 1: 0;
992 my $cache = Koha::Caches->get_instance();
993 my $cache_key = "MarcStructure-$forlibrarian-$frameworkcode";
994 my $cached = $cache->get_from_cache($cache_key, { unsafe => $unsafe });
995 return $cached if $cached;
997 my $dbh = C4::Context->dbh;
998 my $sth = $dbh->prepare(
999 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable,important,ind1_defaultvalue,ind2_defaultvalue
1000 FROM marc_tag_structure
1001 WHERE frameworkcode=?
1004 $sth->execute($frameworkcode);
1005 my ( $liblibrarian, $libopac, $tag, $res, $mandatory, $repeatable, $important, $ind1_defaultvalue, $ind2_defaultvalue );
1007 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable, $important, $ind1_defaultvalue, $ind2_defaultvalue ) = $sth->fetchrow ) {
1008 $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1009 $res->{$tag}->{tab} = "";
1010 $res->{$tag}->{mandatory} = $mandatory;
1011 $res->{$tag}->{important} = $important;
1012 $res->{$tag}->{repeatable} = $repeatable;
1013 $res->{$tag}->{ind1_defaultvalue} = $ind1_defaultvalue;
1014 $res->{$tag}->{ind2_defaultvalue} = $ind2_defaultvalue;
1017 my $mss = Koha::MarcSubfieldStructures->search( { frameworkcode => $frameworkcode } )->unblessed;
1019 $res->{ $m->{tagfield} }->{ $m->{tagsubfield} } = {
1020 lib => ( $forlibrarian or !$m->{libopac} ) ? $m->{liblibrarian} : $m->{libopac},
1021 subfield => $m->{tagsubfield},
1026 $cache->set_in_cache($cache_key, $res);
1030 =head2 GetUsedMarcStructure
1032 The same function as GetMarcStructure except it just takes field
1033 in tab 0-9. (used field)
1035 my $results = GetUsedMarcStructure($frameworkcode);
1037 C<$results> is a ref to an array which each case contains a ref
1038 to a hash which each keys is the columns from marc_subfield_structure
1040 C<$frameworkcode> is the framework code.
1044 sub GetUsedMarcStructure {
1045 my $frameworkcode = shift || '';
1048 FROM marc_subfield_structure
1050 AND frameworkcode = ?
1051 ORDER BY tagfield, display_order, tagsubfield
1053 my $sth = C4::Context->dbh->prepare($query);
1054 $sth->execute($frameworkcode);
1055 return $sth->fetchall_arrayref( {} );
1060 =head2 GetMarcSubfieldStructure
1062 my $structure = GetMarcSubfieldStructure($frameworkcode, [$params]);
1064 Returns a reference to hash representing MARC subfield structure
1065 for framework with framework code C<$frameworkcode>, C<$params> is
1066 optional and may contain additional options.
1070 =item C<$frameworkcode>
1076 An optional hash reference with additional options.
1077 The following options are supported:
1083 Pass { unsafe => 1 } do disable cached object cloning,
1084 and instead get a shared reference, resulting in better
1085 performance (but care must be taken so that retured object
1088 Note: If you call GetMarcSubfieldStructure with unsafe => 1, do not modify or
1089 even autovivify its contents. It is a cached/shared data structure. Your
1090 changes would be passed around in subsequent calls.
1098 sub GetMarcSubfieldStructure {
1099 my ( $frameworkcode, $params ) = @_;
1101 $frameworkcode //= '';
1103 my $cache = Koha::Caches->get_instance();
1104 my $cache_key = "MarcSubfieldStructure-$frameworkcode";
1105 my $cached = $cache->get_from_cache($cache_key, { unsafe => ($params && $params->{unsafe}) });
1106 return $cached if $cached;
1108 my $dbh = C4::Context->dbh;
1109 # We moved to selectall_arrayref since selectall_hashref does not
1110 # keep duplicate mappings on kohafield (like place in 260 vs 264)
1111 my $subfield_aref = $dbh->selectall_arrayref( q|
1113 FROM marc_subfield_structure
1114 WHERE frameworkcode = ?
1116 ORDER BY frameworkcode, tagfield, display_order, tagsubfield
1117 |, { Slice => {} }, $frameworkcode );
1118 # Now map the output to a hash structure
1119 my $subfield_structure = {};
1120 foreach my $row ( @$subfield_aref ) {
1121 push @{ $subfield_structure->{ $row->{kohafield} }}, $row;
1123 $cache->set_in_cache( $cache_key, $subfield_structure );
1124 return $subfield_structure;
1127 =head2 GetMarcFromKohaField
1129 ( $field,$subfield ) = GetMarcFromKohaField( $kohafield );
1130 @fields = GetMarcFromKohaField( $kohafield );
1131 $field = GetMarcFromKohaField( $kohafield );
1133 Returns the MARC fields & subfields mapped to $kohafield.
1134 Since the Default framework is considered as authoritative for such
1135 mappings, the former frameworkcode parameter is obsoleted.
1137 In list context all mappings are returned; there can be multiple
1138 mappings. Note that in the above example you could miss a second
1139 mappings in the first call.
1140 In scalar context only the field tag of the first mapping is returned.
1144 sub GetMarcFromKohaField {
1145 my ( $kohafield ) = @_;
1146 return unless $kohafield;
1147 # The next call uses the Default framework since it is AUTHORITATIVE
1148 # for all Koha to MARC mappings.
1149 my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework
1151 foreach( @{ $mss->{$kohafield} } ) {
1152 push @retval, $_->{tagfield}, $_->{tagsubfield};
1154 return wantarray ? @retval : ( @retval ? $retval[0] : undef );
1157 =head2 GetMarcSubfieldStructureFromKohaField
1159 my $str = GetMarcSubfieldStructureFromKohaField( $kohafield );
1161 Returns marc subfield structure information for $kohafield.
1162 The Default framework is used, since it is authoritative for kohafield
1164 In list context returns a list of all hashrefs, since there may be
1165 multiple mappings. In scalar context the first hashref is returned.
1169 sub GetMarcSubfieldStructureFromKohaField {
1170 my ( $kohafield ) = @_;
1172 return unless $kohafield;
1174 # The next call uses the Default framework since it is AUTHORITATIVE
1175 # for all Koha to MARC mappings.
1176 my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework
1177 return unless $mss->{$kohafield};
1178 return wantarray ? @{$mss->{$kohafield}} : $mss->{$kohafield}->[0];
1181 =head2 GetMarcBiblio
1183 my $record = GetMarcBiblio({
1184 biblionumber => $biblionumber,
1185 embed_items => $embeditems,
1187 borcat => $patron_category });
1189 Returns MARC::Record representing a biblio record, or C<undef> if the
1190 biblionumber doesn't exist.
1192 Both embed_items and opac are optional.
1193 If embed_items is passed and is 1, items are embedded.
1194 If opac is passed and is 1, the record is filtered as needed.
1198 =item C<$biblionumber>
1202 =item C<$embeditems>
1204 set to true to include item information.
1208 set to true to make the result suited for OPAC view. This causes things like
1209 OpacHiddenItems to be applied.
1213 If the OpacHiddenItemsExceptions system preference is set, this patron category
1214 can be used to make visible OPAC items which would be normally hidden.
1215 It only makes sense in combination both embed_items and opac values true.
1224 if (not defined $params) {
1225 carp 'GetMarcBiblio called without parameters';
1229 my $biblionumber = $params->{biblionumber};
1230 my $embeditems = $params->{embed_items} || 0;
1231 my $opac = $params->{opac} || 0;
1232 my $borcat = $params->{borcat} // q{};
1234 if (not defined $biblionumber) {
1235 carp 'GetMarcBiblio called with undefined biblionumber';
1239 my $marcxml = GetXmlBiblio( $biblionumber );
1240 $marcxml = StripNonXmlChars( $marcxml );
1241 MARC::File::XML->default_record_format( C4::Context->preference('marcflavour') );
1242 my $record = MARC::Record->new();
1246 MARC::Record::new_from_xml( $marcxml, "UTF-8",
1247 C4::Context->preference('marcflavour') );
1249 if ($@) { warn " problem with :$biblionumber : $@ \n$marcxml"; }
1250 return unless $record;
1252 C4::Biblio::EmbedItemsInMarcBiblio({
1253 marc_record => $record,
1254 biblionumber => $biblionumber,
1256 borcat => $borcat })
1268 my $marcxml = GetXmlBiblio($biblionumber);
1270 Returns biblio_metadata.metadata/marcxml of the biblionumber passed in parameter.
1271 The XML should only contain biblio information (item information is no longer stored in marcxml field)
1276 my ($biblionumber) = @_;
1277 my $dbh = C4::Context->dbh;
1278 return unless $biblionumber;
1279 my ($marcxml) = $dbh->selectrow_array(
1282 FROM biblio_metadata
1283 WHERE biblionumber=?
1284 AND format='marcxml'
1286 |, undef, $biblionumber, C4::Context->preference('marcflavour')
1293 return the prices in accordance with the Marc format.
1295 returns 0 if no price found
1296 returns undef if called without a marc record or with
1297 an unrecognized marc format
1302 my ( $record, $marcflavour ) = @_;
1304 carp 'GetMarcPrice called on undefined record';
1311 if ( $marcflavour eq "MARC21" ) {
1312 @listtags = ('345', '020');
1314 } elsif ( $marcflavour eq "UNIMARC" ) {
1315 @listtags = ('345', '010');
1321 for my $field ( $record->field(@listtags) ) {
1322 for my $subfield_value ($field->subfield($subfield)){
1324 $subfield_value = MungeMarcPrice( $subfield_value );
1325 return $subfield_value if ($subfield_value);
1328 return 0; # no price found
1331 =head2 MungeMarcPrice
1333 Return the best guess at what the actual price is from a price field.
1337 sub MungeMarcPrice {
1339 return unless ( $price =~ m/\d/ ); ## No digits means no price.
1340 # Look for the currency symbol and the normalized code of the active currency, if it's there,
1341 my $active_currency = Koha::Acquisition::Currencies->get_active;
1342 my $symbol = $active_currency->symbol;
1343 my $isocode = $active_currency->isocode;
1344 $isocode = $active_currency->currency unless defined $isocode;
1347 my @matches =($price=~ /
1349 ( # start of capturing parenthesis
1351 (?:[\p{Sc}\p{L}\/.]){1,4} # any character from Currency signs or Letter Unicode categories or slash or dot within 1 to 4 occurrences : call this whole block 'symbol block'
1352 |(?:\d+[\p{P}\s]?){1,4} # or else at least one digit followed or not by a punctuation sign or whitespace, all these within 1 to 4 occurrences : call this whole block 'digits block'
1354 \s?\p{Sc}?\s? # followed or not by a whitespace. \p{Sc}?\s? are for cases like '25$ USD'
1356 (?:[\p{Sc}\p{L}\/.]){1,4} # followed by same block as symbol block
1357 |(?:\d+[\p{P}\s]?){1,4} # or by same block as digits block
1359 \s?\p{L}{0,4}\s? # followed or not by a whitespace. \p{L}{0,4}\s? are for cases like '$9.50 USD'
1360 ) # end of capturing parenthesis
1361 (?:\p{P}|\z) # followed by a punctuation sign or by the end of the string
1365 foreach ( @matches ) {
1366 $localprice = $_ and last if index($_, $isocode)>=0;
1368 if ( !$localprice ) {
1369 foreach ( @matches ) {
1370 $localprice = $_ and last if $_=~ /(^|[^\p{Sc}\p{L}\/])\Q$symbol\E([^\p{Sc}\p{L}\/]+\z|\z)/;
1375 if ( $localprice ) {
1376 $price = $localprice;
1378 ## Grab the first number in the string ( can use commas or periods for thousands separator and/or decimal separator )
1379 ( $price ) = $price =~ m/([\d\,\.]+[[\,\.]\d\d]?)/;
1381 # eliminate symbol/isocode, space and any final dot from the string
1382 $price =~ s/[\p{Sc}\p{L}\/ ]|\.$//g;
1383 # remove comma,dot when used as separators from hundreds
1384 $price =~s/[\,\.](\d{3})/$1/g;
1385 # convert comma to dot to ensure correct display of decimals if existing
1391 =head2 GetMarcQuantity
1393 return the quantity of a book. Used in acquisition only, when importing a file an iso2709 from a bookseller
1394 Warning : this is not really in the marc standard. In Unimarc, Electre (the most widely used bookseller) use the 969$a
1396 returns 0 if no quantity found
1397 returns undef if called without a marc record or with
1398 an unrecognized marc format
1402 sub GetMarcQuantity {
1403 my ( $record, $marcflavour ) = @_;
1405 carp 'GetMarcQuantity called on undefined record';
1412 if ( $marcflavour eq "MARC21" ) {
1414 } elsif ( $marcflavour eq "UNIMARC" ) {
1415 @listtags = ('969');
1421 for my $field ( $record->field(@listtags) ) {
1422 for my $subfield_value ($field->subfield($subfield)){
1424 if ($subfield_value) {
1425 # in France, the cents separator is the , but sometimes, ppl use a .
1426 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
1427 $subfield_value =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
1428 return $subfield_value;
1432 return 0; # no price found
1436 =head2 GetAuthorisedValueDesc
1438 my $subfieldvalue =get_authorised_value_desc(
1439 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category, $opac);
1441 Retrieve the complete description for a given authorised value.
1443 Now takes $category and $value pair too.
1445 my $auth_value_desc =GetAuthorisedValueDesc(
1446 '','', 'DVD' ,'','','CCODE');
1448 If the optional $opac parameter is set to a true value, displays OPAC
1449 descriptions rather than normal ones when they exist.
1453 sub GetAuthorisedValueDesc {
1454 my ( $tag, $subfield, $value, $framework, $tagslib, $category, $opac ) = @_;
1458 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1461 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1462 my $branch = Koha::Libraries->find($value);
1463 return $branch? $branch->branchname: q{};
1467 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1468 my $itemtype = Koha::ItemTypes->find( $value );
1469 return $itemtype ? $itemtype->translated_description : q||;
1472 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "cn_source" ) {
1473 my $source = GetClassSource($value);
1474 return $source ? $source->{description} : q||;
1477 #---- "true" authorized value
1478 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1481 my $dbh = C4::Context->dbh;
1482 if ( $category ne "" ) {
1483 my $sth = $dbh->prepare( "SELECT lib, lib_opac FROM authorised_values WHERE category = ? AND authorised_value = ?" );
1484 $sth->execute( $category, $value );
1485 my $data = $sth->fetchrow_hashref;
1486 return ( $opac && $data->{'lib_opac'} ) ? $data->{'lib_opac'} : $data->{'lib'};
1488 return $value; # if nothing is found return the original value
1492 =head2 GetMarcControlnumber
1494 $marccontrolnumber = GetMarcControlnumber($record,$marcflavour);
1496 Get the control number / record Identifier from the MARC record and return it.
1500 sub GetMarcControlnumber {
1501 my ( $record, $marcflavour ) = @_;
1503 carp 'GetMarcControlnumber called on undefined record';
1506 my $controlnumber = "";
1507 # Control number or Record identifier are the same field in MARC21 and UNIMARC
1508 # Keep $marcflavour for possible later use
1509 if ($marcflavour eq "MARC21" || $marcflavour eq "UNIMARC" ) {
1510 my $controlnumberField = $record->field('001');
1511 if ($controlnumberField) {
1512 $controlnumber = $controlnumberField->data();
1515 return $controlnumber;
1520 $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
1522 Get all ISBNs from the MARC record and returns them in an array.
1523 ISBNs stored in different fields depending on MARC flavour
1528 my ( $record, $marcflavour ) = @_;
1530 carp 'GetMarcISBN called on undefined record';
1534 if ( $marcflavour eq "UNIMARC" ) {
1536 } else { # assume marc21 if not unimarc
1541 foreach my $field ( $record->field($scope) ) {
1542 my $isbn = $field->subfield( 'a' );
1543 if ( $isbn && $isbn ne "" ) {
1544 push @marcisbns, $isbn;
1554 $marcissnsarray = GetMarcISSN( $record, $marcflavour );
1556 Get all valid ISSNs from the MARC record and returns them in an array.
1557 ISSNs are stored in different fields depending on MARC flavour
1562 my ( $record, $marcflavour ) = @_;
1564 carp 'GetMarcISSN called on undefined record';
1568 if ( $marcflavour eq "UNIMARC" ) {
1571 else { # assume MARC21
1575 foreach my $field ( $record->field($scope) ) {
1576 push @marcissns, $field->subfield( 'a' )
1577 if ( $field->subfield( 'a' ) ne "" );
1582 =head2 GetMarcSubjects
1584 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1586 Get all subjects from the MARC record and returns them in an array.
1587 The subjects are stored in different fields depending on MARC flavour
1591 sub GetMarcSubjects {
1592 my ( $record, $marcflavour ) = @_;
1594 carp 'GetMarcSubjects called on undefined record';
1597 my ( $mintag, $maxtag, $fields_filter );
1598 if ( $marcflavour eq "UNIMARC" ) {
1601 $fields_filter = '6..';
1605 $fields_filter = '6..';
1610 my $subject_limit = C4::Context->preference("TraceCompleteSubfields") ? 'su,complete-subfield' : 'su';
1611 my $AuthoritySeparator = C4::Context->preference('AuthoritySeparator');
1613 foreach my $field ( $record->field($fields_filter) ) {
1614 next unless ($field->tag() >= $mintag && $field->tag() <= $maxtag);
1616 my @subfields = $field->subfields();
1619 # if there is an authority link, build the links with an= subfield9
1620 my $subfield9 = $field->subfield('9');
1623 my $linkvalue = $subfield9;
1624 $linkvalue =~ s/(\(|\))//g;
1625 @link_loop = ( { limit => 'an', 'link' => $linkvalue } );
1626 $authoritylink = $linkvalue
1630 for my $subject_subfield (@subfields) {
1631 next if ( $subject_subfield->[0] eq '9' );
1633 # don't load unimarc subfields 3,4,5
1634 next if ( ( $marcflavour eq "UNIMARC" ) and ( $subject_subfield->[0] =~ /2|3|4|5/ ) );
1635 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1636 next if ( ( $marcflavour eq "MARC21" ) and ( $subject_subfield->[0] =~ /2/ ) );
1638 my $code = $subject_subfield->[0];
1639 my $value = $subject_subfield->[1];
1640 my $linkvalue = $value;
1641 $linkvalue =~ s/(\(|\))//g;
1642 # if no authority link, build a search query
1643 unless ($subfield9) {
1645 limit => $subject_limit,
1646 'link' => $linkvalue,
1647 operator => (scalar @link_loop) ? ' AND ' : undef
1650 my @this_link_loop = @link_loop;
1652 unless ( $code eq '0' ) {
1653 push @subfields_loop, {
1656 link_loop => \@this_link_loop,
1657 separator => (scalar @subfields_loop) ? $AuthoritySeparator : ''
1662 push @marcsubjects, {
1663 MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop,
1664 authoritylink => $authoritylink,
1665 } if $authoritylink || @subfields_loop;
1668 return \@marcsubjects;
1669 } #end getMARCsubjects
1673 $marcurls = GetMarcUrls($record,$marcflavour);
1675 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1676 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1681 my ( $record, $marcflavour ) = @_;
1683 carp 'GetMarcUrls called on undefined record';
1688 for my $field ( $record->field('856') ) {
1690 for my $note ( $field->subfield('z') ) {
1691 push @notes, { note => $note };
1693 my @urls = $field->subfield('u');
1694 foreach my $url (@urls) {
1695 $url =~ s/^\s+|\s+$//g; # trim
1697 if ( $marcflavour eq 'MARC21' ) {
1698 my $s3 = $field->subfield('3');
1699 my $link = $field->subfield('y');
1700 unless ( $url =~ /^\w+:/ ) {
1701 if ( $field->indicator(1) eq '7' ) {
1702 $url = $field->subfield('2') . "://" . $url;
1703 } elsif ( $field->indicator(1) eq '1' ) {
1704 $url = 'ftp://' . $url;
1707 # properly, this should be if ind1=4,
1708 # however we will assume http protocol since we're building a link.
1709 $url = 'http://' . $url;
1713 # TODO handle ind 2 (relationship)
1718 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1719 $marcurl->{'part'} = $s3 if ($link);
1720 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1722 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1723 $marcurl->{'MARCURL'} = $url;
1725 push @marcurls, $marcurl;
1731 =head2 GetMarcSeries
1733 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1735 Get all series from the MARC record and returns them in an array.
1736 The series are stored in different fields depending on MARC flavour
1741 my ( $record, $marcflavour ) = @_;
1743 carp 'GetMarcSeries called on undefined record';
1747 my ( $mintag, $maxtag, $fields_filter );
1748 if ( $marcflavour eq "UNIMARC" ) {
1751 $fields_filter = '2..';
1755 $fields_filter = '4..';
1759 my $AuthoritySeparator = C4::Context->preference('AuthoritySeparator');
1761 foreach my $field ( $record->field($fields_filter) ) {
1762 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1764 my @subfields = $field->subfields();
1767 for my $series_subfield (@subfields) {
1769 # ignore $9, used for authority link
1770 next if ( $series_subfield->[0] eq '9' );
1773 my $code = $series_subfield->[0];
1774 my $value = $series_subfield->[1];
1775 my $linkvalue = $value;
1776 $linkvalue =~ s/(\(|\))//g;
1778 # see if this is an instance of a volume
1779 if ( $code eq 'v' ) {
1784 'link' => $linkvalue,
1785 operator => (scalar @link_loop) ? ' AND ' : undef
1788 if ($volume_number) {
1789 push @subfields_loop, { volumenum => $value };
1791 push @subfields_loop, {
1794 link_loop => \@link_loop,
1795 separator => (scalar @subfields_loop) ? $AuthoritySeparator : '',
1796 volumenum => $volume_number,
1800 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1803 return \@marcseries;
1804 } #end getMARCseriess
1806 =head2 UpsertMarcSubfield
1808 my $record = C4::Biblio::UpsertMarcSubfield($MARC::Record, $fieldTag, $subfieldCode, $subfieldContent);
1812 sub UpsertMarcSubfield {
1813 my ($record, $tag, $code, $content) = @_;
1814 my $f = $record->field($tag);
1817 $f->update( $code => $content );
1820 my $f = MARC::Field->new( $tag, '', '', $code => $content);
1821 $record->insert_fields_ordered( $f );
1825 =head2 UpsertMarcControlField
1827 my $record = C4::Biblio::UpsertMarcControlField($MARC::Record, $fieldTag, $content);
1831 sub UpsertMarcControlField {
1832 my ($record, $tag, $content) = @_;
1833 die "UpsertMarcControlField() \$tag '$tag' is not a control field\n" unless 0+$tag < 10;
1834 my $f = $record->field($tag);
1837 $f->update( $content );
1840 my $f = MARC::Field->new($tag, $content);
1841 $record->insert_fields_ordered( $f );
1845 =head2 GetFrameworkCode
1847 $frameworkcode = GetFrameworkCode( $biblionumber )
1851 sub GetFrameworkCode {
1852 my ($biblionumber) = @_;
1853 my $dbh = C4::Context->dbh;
1854 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1855 $sth->execute($biblionumber);
1856 my ($frameworkcode) = $sth->fetchrow;
1857 return $frameworkcode;
1860 =head2 TransformKohaToMarc
1862 $record = TransformKohaToMarc( $hash [, $params ] )
1864 This function builds a (partial) MARC::Record from a hash.
1865 Hash entries can be from biblio, biblioitems or items.
1866 The params hash includes the parameter no_split used in C4::Items.
1868 This function is called in acquisition module, to create a basic catalogue
1869 entry from user entry.
1874 sub TransformKohaToMarc {
1875 my ( $hash, $params ) = @_;
1876 my $record = MARC::Record->new();
1877 SetMarcUnicodeFlag( $record, C4::Context->preference("marcflavour") );
1879 # In the next call we use the Default framework, since it is considered
1880 # authoritative for Koha to Marc mappings.
1881 my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # do not change framework
1883 while ( my ($kohafield, $value) = each %$hash ) {
1884 foreach my $fld ( @{ $mss->{$kohafield} } ) {
1885 my $tagfield = $fld->{tagfield};
1886 my $tagsubfield = $fld->{tagsubfield};
1889 # BZ 21800: split value if field is repeatable.
1890 my @values = _check_split($params, $fld, $value)
1891 ? split(/\s?\|\s?/, $value, -1)
1893 foreach my $value ( @values ) {
1894 next if $value eq '';
1895 $tag_hr->{$tagfield} //= [];
1896 push @{$tag_hr->{$tagfield}}, [($tagsubfield, $value)];
1900 foreach my $tag (sort keys %$tag_hr) {
1901 my @sfl = @{$tag_hr->{$tag}};
1902 @sfl = sort { $a->[0] cmp $b->[0]; } @sfl;
1903 @sfl = map { @{$_}; } @sfl;
1904 # Special care for control fields: remove the subfield indication @
1905 # and do not insert indicators.
1906 my @ind = $tag < 10 ? () : ( " ", " " );
1907 @sfl = grep { $_ ne '@' } @sfl if $tag < 10;
1908 $record->insert_fields_ordered( MARC::Field->new($tag, @ind, @sfl) );
1914 # Checks if $value must be split; may consult passed framework
1915 my ($params, $fld, $value) = @_;
1916 return if index($value,'|') == -1; # nothing to worry about
1917 return if $params->{no_split};
1919 # if we did not get a specific framework, check default in $mss
1920 return $fld->{repeatable} if !$params->{framework};
1922 # here we need to check the specific framework
1923 my $mss = GetMarcSubfieldStructure($params->{framework}, { unsafe => 1 });
1924 foreach my $fld2 ( @{ $mss->{ $fld->{kohafield} } } ) {
1925 next if $fld2->{tagfield} ne $fld->{tagfield};
1926 next if $fld2->{tagsubfield} ne $fld->{tagsubfield};
1927 return 1 if $fld2->{repeatable};
1932 =head2 PrepHostMarcField
1934 $hostfield = PrepHostMarcField ( $hostbiblionumber,$hostitemnumber,$marcflavour )
1936 This function returns a host field populated with data from the host record, the field can then be added to an analytical record
1940 sub PrepHostMarcField {
1941 my ($hostbiblionumber,$hostitemnumber, $marcflavour) = @_;
1942 $marcflavour ||="MARC21";
1944 my $hostrecord = GetMarcBiblio({ biblionumber => $hostbiblionumber });
1945 my $item = Koha::Items->find($hostitemnumber);
1948 if ( $marcflavour eq "MARC21" ) {
1952 if ($hostrecord->subfield('100','a')){
1953 $mainentry = $hostrecord->subfield('100','a');
1954 } elsif ($hostrecord->subfield('110','a')){
1955 $mainentry = $hostrecord->subfield('110','a');
1957 $mainentry = $hostrecord->subfield('111','a');
1960 # qualification info
1962 if (my $field260 = $hostrecord->field('260')){
1963 $qualinfo = $field260->as_string( 'abc' );
1968 my $ed = $hostrecord->subfield('250','a');
1969 my $barcode = $item->barcode;
1970 my $title = $hostrecord->subfield('245','a');
1972 # record control number, 001 with 003 and prefix
1974 if ($hostrecord->field('001')){
1975 $recctrlno = $hostrecord->field('001')->data();
1976 if ($hostrecord->field('003')){
1977 $recctrlno = '('.$hostrecord->field('003')->data().')'.$recctrlno;
1982 my $issn = $hostrecord->subfield('022','a');
1983 my $isbn = $hostrecord->subfield('020','a');
1986 $hostmarcfield = MARC::Field->new(
1988 '0' => $hostbiblionumber,
1989 '9' => $hostitemnumber,
1999 } elsif ($marcflavour eq "UNIMARC") {
2000 $hostmarcfield = MARC::Field->new(
2002 '0' => $hostbiblionumber,
2003 't' => $hostrecord->subfield('200','a'),
2004 '9' => $hostitemnumber
2008 return $hostmarcfield;
2011 =head2 TransformHtmlToXml
2013 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator,
2014 $ind_tag, $auth_type )
2016 $auth_type contains :
2020 =item - nothing : rebuild a biblio. In UNIMARC the encoding is in 100$a pos 26/27
2022 =item - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
2024 =item - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
2030 sub TransformHtmlToXml {
2031 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
2032 # NOTE: The parameter $ind_tag is NOT USED -- BZ 11247
2034 my ( $perm_loc_tag, $perm_loc_subfield ) = C4::Biblio::GetMarcFromKohaField( "items.permanent_location" );
2036 my $xml = MARC::File::XML::header('UTF-8');
2037 $xml .= "<record>\n";
2038 $auth_type = C4::Context->preference('marcflavour') unless $auth_type; # FIXME auth_type must be removed
2039 MARC::File::XML->default_record_format($auth_type);
2041 # in UNIMARC, field 100 contains the encoding
2042 # check that there is one, otherwise the
2043 # MARC::Record->new_from_xml will fail (and Koha will die)
2044 my $unimarc_and_100_exist = 0;
2045 $unimarc_and_100_exist = 1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2050 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
2051 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a" ) {
2053 # if we have a 100 field and it's values are not correct, skip them.
2054 # if we don't have any valid 100 field, we will create a default one at the end
2055 my $enc = substr( @$values[$i], 26, 2 );
2056 if ( $enc eq '01' or $enc eq '50' or $enc eq '03' ) {
2057 $unimarc_and_100_exist = 1;
2062 @$values[$i] =~ s/&/&/g;
2063 @$values[$i] =~ s/</</g;
2064 @$values[$i] =~ s/>/>/g;
2065 @$values[$i] =~ s/"/"/g;
2066 @$values[$i] =~ s/'/'/g;
2068 my $skip = @$values[$i] eq q{};
2071 && $perm_loc_subfield
2072 && @$tags[$i] eq $perm_loc_tag
2073 && @$subfields[$i] eq $perm_loc_subfield;
2075 if ( ( @$tags[$i] ne $prevtag ) ) {
2076 $close_last_tag = 0;
2077 $j++ unless ( @$tags[$i] eq "" );
2078 my $str = ( $indicator->[$j] // q{} ) . ' '; # extra space prevents substr outside of string warn
2079 my $ind1 = _default_ind_to_space( substr( $str, 0, 1 ) );
2080 my $ind2 = _default_ind_to_space( substr( $str, 1, 1 ) );
2082 $xml .= "</datafield>\n";
2083 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2085 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2086 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2088 $close_last_tag = 1;
2096 if ( @$tags[$i] eq "000" ) {
2097 $xml .= "<leader>@$values[$i]</leader>\n";
2100 # rest of the fixed fields
2101 } elsif ( @$tags[$i] < 10 ) {
2102 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2105 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2106 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2108 $close_last_tag = 1;
2112 } else { # @$tags[$i] eq $prevtag
2115 my $str = ( $indicator->[$j] // q{} ) . ' '; # extra space prevents substr outside of string warn
2116 my $ind1 = _default_ind_to_space( substr( $str, 0, 1 ) );
2117 my $ind2 = _default_ind_to_space( substr( $str, 1, 1 ) );
2118 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2120 $close_last_tag = 1;
2122 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2125 $prevtag = @$tags[$i];
2127 $xml .= "</datafield>\n" if $close_last_tag;
2128 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist ) {
2130 # warn "SETTING 100 for $auth_type";
2131 my $string = strftime( "%Y%m%d", localtime(time) );
2133 # set 50 to position 26 is biblios, 13 if authorities
2135 $pos = 13 if $auth_type eq 'UNIMARCAUTH';
2136 $string = sprintf( "%-*s", 35, $string );
2137 substr( $string, $pos, 6, "50" );
2138 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2139 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2140 $xml .= "</datafield>\n";
2142 $xml .= "</record>\n";
2143 $xml .= MARC::File::XML::footer();
2147 =head2 _default_ind_to_space
2149 Passed what should be an indicator returns a space
2150 if its undefined or zero length
2154 sub _default_ind_to_space {
2156 if ( !defined $s || $s eq q{} ) {
2162 =head2 TransformHtmlToMarc
2164 L<$record> = TransformHtmlToMarc(L<$cgi>)
2165 L<$cgi> is the CGI object which contains the values for subfields
2167 'tag_010_indicator1_531951' ,
2168 'tag_010_indicator2_531951' ,
2169 'tag_010_code_a_531951_145735' ,
2170 'tag_010_subfield_a_531951_145735' ,
2171 'tag_200_indicator1_873510' ,
2172 'tag_200_indicator2_873510' ,
2173 'tag_200_code_a_873510_673465' ,
2174 'tag_200_subfield_a_873510_673465' ,
2175 'tag_200_code_b_873510_704318' ,
2176 'tag_200_subfield_b_873510_704318' ,
2177 'tag_200_code_e_873510_280822' ,
2178 'tag_200_subfield_e_873510_280822' ,
2179 'tag_200_code_f_873510_110730' ,
2180 'tag_200_subfield_f_873510_110730' ,
2182 L<$record> is the MARC::Record object.
2186 sub TransformHtmlToMarc {
2187 my ($cgi, $isbiblio) = @_;
2189 my @params = $cgi->multi_param();
2191 # explicitly turn on the UTF-8 flag for all
2192 # 'tag_' parameters to avoid incorrect character
2193 # conversion later on
2194 my $cgi_params = $cgi->Vars;
2195 foreach my $param_name ( keys %$cgi_params ) {
2196 if ( $param_name =~ /^tag_/ ) {
2197 my $param_value = $cgi_params->{$param_name};
2198 unless ( Encode::is_utf8( $param_value ) ) {
2199 $cgi_params->{$param_name} = Encode::decode('UTF-8', $param_value );
2204 # creating a new record
2205 my $record = MARC::Record->new();
2207 my ($biblionumbertagfield, $biblionumbertagsubfield) = (-1, -1);
2208 ($biblionumbertagfield, $biblionumbertagsubfield) =
2209 &GetMarcFromKohaField( "biblio.biblionumber", '' ) if $isbiblio;
2210 #FIXME This code assumes that the CGI params will be in the same order as the fields in the template; this is no absolute guarantee!
2211 for (my $i = 0; $params[$i]; $i++ ) { # browse all CGI params
2212 my $param = $params[$i];
2215 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2216 if ( $param eq 'biblionumber' ) {
2217 if ( $biblionumbertagfield < 10 ) {
2218 $newfield = MARC::Field->new( $biblionumbertagfield, scalar $cgi->param($param), );
2220 $newfield = MARC::Field->new( $biblionumbertagfield, '', '', "$biblionumbertagsubfield" => scalar $cgi->param($param), );
2222 push @fields, $newfield if ($newfield);
2223 } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..."
2226 my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) );
2227 my $ind2 = _default_ind_to_space( substr( $cgi->param( $params[ $i + 1 ] ), 0, 1 ) );
2231 if ( $tag < 10 ) { # no code for theses fields
2232 # in MARC editor, 000 contains the leader.
2233 next if $tag == $biblionumbertagfield;
2234 my $fval= $cgi->param($params[$j+1]);
2235 if ( $tag eq '000' ) {
2236 # Force a fake leader even if not provided to avoid crashing
2237 # during decoding MARC record containing UTF-8 characters
2239 length( $fval ) == 24
2244 # between 001 and 009 (included)
2245 } elsif ( $fval ne '' ) {
2246 $newfield = MARC::Field->new( $tag, $fval, );
2249 # > 009, deal with subfields
2251 # browse subfields for this tag (reason for _code_ match)
2252 while(defined $params[$j] && $params[$j] =~ /_code_/) {
2253 last unless defined $params[$j+1];
2255 if $tag == $biblionumbertagfield and
2256 $cgi->param($params[$j]) eq $biblionumbertagsubfield;
2257 #if next param ne subfield, then it was probably empty
2258 #try next param by incrementing j
2259 if($params[$j+1]!~/_subfield_/) {$j++; next; }
2260 my $fkey= $cgi->param($params[$j]);
2261 my $fval= $cgi->param($params[$j+1]);
2262 #check if subfield value not empty and field exists
2263 if($fval ne '' && $newfield) {
2264 $newfield->add_subfields( $fkey => $fval);
2266 elsif($fval ne '') {
2267 $newfield = MARC::Field->new( $tag, $ind1, $ind2, $fkey => $fval );
2271 $i= $j-1; #update i for outer loop accordingly
2273 push @fields, $newfield if ($newfield);
2277 @fields = sort { $a->tag() cmp $b->tag() } @fields;
2278 $record->append_fields(@fields);
2282 =head2 TransformMarcToKoha
2284 $result = TransformMarcToKoha( $record, undef, $limit )
2286 Extract data from a MARC bib record into a hashref representing
2287 Koha biblio, biblioitems, and items fields.
2289 If passed an undefined record will log the error and return an empty
2294 sub TransformMarcToKoha {
2295 my ( $record, $frameworkcode, $limit_table ) = @_;
2296 # FIXME Parameter $frameworkcode is obsolete and will be removed
2297 $limit_table //= q{};
2300 if (!defined $record) {
2301 carp('TransformMarcToKoha called with undefined record');
2305 my %tables = ( biblio => 1, biblioitems => 1, items => 1 );
2306 if( $limit_table eq 'items' ) {
2307 %tables = ( items => 1 );
2308 } elsif ( $limit_table eq 'no_items' ){
2309 %tables = ( biblio => 1, biblioitems => 1 );
2312 # The next call acknowledges Default as the authoritative framework
2313 # for Koha to MARC mappings.
2314 my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework
2315 foreach my $kohafield ( keys %{ $mss } ) {
2316 my ( $table, $column ) = split /[.]/, $kohafield, 2;
2317 next unless $tables{$table};
2318 my $val = TransformMarcToKohaOneField( $kohafield, $record );
2319 next if !defined $val;
2320 my $key = _disambiguate( $table, $column );
2321 $result->{$key} = $val;
2326 =head2 _disambiguate
2328 $newkey = _disambiguate($table, $field);
2330 This is a temporary hack to distinguish between the
2331 following sets of columns when using TransformMarcToKoha.
2333 items.cn_source & biblioitems.cn_source
2334 items.cn_sort & biblioitems.cn_sort
2336 Columns that are currently NOT distinguished (FIXME
2337 due to lack of time to fully test) are:
2339 biblio.notes and biblioitems.notes
2344 FIXME - this is necessary because prefixing each column
2345 name with the table name would require changing lots
2346 of code and templates, and exposing more of the DB
2347 structure than is good to the UI templates, particularly
2348 since biblio and bibloitems may well merge in a future
2349 version. In the future, it would also be good to
2350 separate DB access and UI presentation field names
2356 my ( $table, $column ) = @_;
2357 if ( $column eq "cn_sort" or $column eq "cn_source" ) {
2358 return $table . '.' . $column;
2365 =head2 TransformMarcToKohaOneField
2367 $val = TransformMarcToKohaOneField( 'biblio.title', $marc );
2369 Note: The authoritative Default framework is used implicitly.
2373 sub TransformMarcToKohaOneField {
2374 my ( $kohafield, $marc ) = @_;
2376 my ( @rv, $retval );
2377 my @mss = GetMarcSubfieldStructureFromKohaField($kohafield);
2378 foreach my $fldhash ( @mss ) {
2379 my $tag = $fldhash->{tagfield};
2380 my $sub = $fldhash->{tagsubfield};
2381 foreach my $fld ( $marc->field($tag) ) {
2382 if( $sub eq '@' || $fld->is_control_field ) {
2383 push @rv, $fld->data if $fld->data;
2385 push @rv, grep { $_ } $fld->subfield($sub);
2390 $retval = join ' | ', uniq(@rv);
2392 # Additional polishing for individual kohafields
2393 if( $kohafield =~ /copyrightdate|publicationyear/ ) {
2394 $retval = _adjust_pubyear( $retval );
2400 =head2 _adjust_pubyear
2402 Helper routine for TransformMarcToKohaOneField
2406 sub _adjust_pubyear {
2408 # modify return value to keep only the 1st year found
2409 if( $retval =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2411 } elsif( $retval =~ m/(\d\d\d\d)/ && $1 > 0 ) {
2413 } elsif( $retval =~ m/(?<year>\d{1,3})[.Xx?-]/ ) {
2414 # See also bug 24674: enough to look at one unknown year char like .Xx-?
2415 # At this point in code 1234? or 1234- already passed the earlier regex
2416 # Things like 2-, 1xx, 1??? are now converted to a four positions-year.
2417 $retval = $+{year} * ( 10 ** (4-length($+{year})) );
2424 =head2 CountItemsIssued
2426 my $count = CountItemsIssued( $biblionumber );
2430 sub CountItemsIssued {
2431 my ($biblionumber) = @_;
2432 my $dbh = C4::Context->dbh;
2433 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2434 $sth->execute($biblionumber);
2435 my $row = $sth->fetchrow_hashref();
2436 return $row->{'issuedCount'};
2441 ModZebra( $record_number, $op, $server );
2443 $record_number is the authid or biblionumber we want to index
2445 $op is the operation: specialUpdate or recordDelete
2447 $server is authorityserver or biblioserver
2452 my ( $record_number, $op, $server ) = @_;
2453 Koha::Logger->get->debug("ModZebra: updates requested for: $record_number $op $server");
2454 my $dbh = C4::Context->dbh;
2456 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2458 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2459 # the table is emptied by rebuild_zebra.pl script (using the -z switch)
2460 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2462 AND biblio_auth_number = ?
2465 my $check_sth = $dbh->prepare_cached($check_sql);
2466 $check_sth->execute( $server, $record_number, $op );
2467 my ($count) = $check_sth->fetchrow_array;
2468 $check_sth->finish();
2469 if ( $count == 0 ) {
2470 my $sth = $dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2471 $sth->execute( $record_number, $server, $op );
2476 =head2 EmbedItemsInMarcBiblio
2478 EmbedItemsInMarcBiblio({
2479 marc_record => $marc,
2480 biblionumber => $biblionumber,
2481 item_numbers => $itemnumbers,
2484 Given a MARC::Record object containing a bib record,
2485 modify it to include the items attached to it as 9XX
2486 per the bib's MARC framework.
2487 if $itemnumbers is defined, only specified itemnumbers are embedded.
2489 If $opac is true, then opac-relevant suppressions are included.
2491 If opac filtering will be done, borcat should be passed to properly
2492 override if necessary.
2496 sub EmbedItemsInMarcBiblio {
2498 my ($marc, $biblionumber, $itemnumbers, $opac, $borcat);
2499 $marc = $params->{marc_record};
2501 carp 'EmbedItemsInMarcBiblio: No MARC record passed';
2504 $biblionumber = $params->{biblionumber};
2505 $itemnumbers = $params->{item_numbers};
2506 $opac = $params->{opac};
2507 $borcat = $params->{borcat} // q{};
2509 $itemnumbers = [] unless defined $itemnumbers;
2511 my $frameworkcode = GetFrameworkCode($biblionumber);
2512 _strip_item_fields($marc, $frameworkcode);
2514 # ... and embed the current items
2515 my $dbh = C4::Context->dbh;
2516 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
2517 $sth->execute($biblionumber);
2518 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" );
2520 my @item_fields; # Array holding the actual MARC data for items to be included.
2521 my @items; # Array holding items which are both in the list (sitenumbers)
2522 # and on this biblionumber
2524 # Flag indicating if there is potential hiding.
2525 my $opachiddenitems = $opac
2526 && ( C4::Context->preference('OpacHiddenItems') !~ /^\s*$/ );
2528 while ( my ($itemnumber) = $sth->fetchrow_array ) {
2529 next if @$itemnumbers and not grep { $_ == $itemnumber } @$itemnumbers;
2531 if ( $opachiddenitems ) {
2532 $item = Koha::Items->find($itemnumber);
2533 $item = $item ? $item->unblessed : undef;
2535 push @items, { itemnumber => $itemnumber, item => $item };
2537 my @items2pass = map { $_->{item} } @items;
2540 ? C4::Items::GetHiddenItemnumbers({
2541 items => \@items2pass,
2542 borcat => $borcat })
2544 # Convert to a hash for quick searching
2545 my %hiddenitems = map { $_ => 1 } @hiddenitems;
2546 foreach my $itemnumber ( map { $_->{itemnumber} } @items ) {
2547 next if $hiddenitems{$itemnumber};
2548 my $item_marc = C4::Items::GetMarcItem( $biblionumber, $itemnumber );
2549 push @item_fields, $item_marc->field($itemtag);
2551 $marc->append_fields(@item_fields);
2554 =head1 INTERNAL FUNCTIONS
2556 =head2 _koha_marc_update_bib_ids
2559 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2561 Internal function to add or update biblionumber and biblioitemnumber to
2566 sub _koha_marc_update_bib_ids {
2567 my ( $record, $frameworkcode, $biblionumber, $biblioitemnumber ) = @_;
2569 my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField( "biblio.biblionumber" );
2570 die qq{No biblionumber tag for framework "$frameworkcode"} unless $biblio_tag;
2571 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
2572 die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag;
2574 if ( $biblio_tag < 10 ) {
2575 C4::Biblio::UpsertMarcControlField( $record, $biblio_tag, $biblionumber );
2577 C4::Biblio::UpsertMarcSubfield($record, $biblio_tag, $biblio_subfield, $biblionumber);
2579 if ( $biblioitem_tag < 10 ) {
2580 C4::Biblio::UpsertMarcControlField( $record, $biblioitem_tag, $biblioitemnumber );
2582 C4::Biblio::UpsertMarcSubfield($record, $biblioitem_tag, $biblioitem_subfield, $biblioitemnumber);
2586 =head2 _koha_marc_update_biblioitem_cn_sort
2588 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2590 Given a MARC bib record and the biblioitem hash, update the
2591 subfield that contains a copy of the value of biblioitems.cn_sort.
2595 sub _koha_marc_update_biblioitem_cn_sort {
2597 my $biblioitem = shift;
2598 my $frameworkcode = shift;
2600 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.cn_sort" );
2601 return unless $biblioitem_tag;
2603 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2605 if ( my $field = $marc->field($biblioitem_tag) ) {
2606 $field->delete_subfield( code => $biblioitem_subfield );
2607 if ( $cn_sort ne '' ) {
2608 $field->add_subfields( $biblioitem_subfield => $cn_sort );
2612 # if we get here, no biblioitem tag is present in the MARC record, so
2613 # we'll create it if $cn_sort is not empty -- this would be
2614 # an odd combination of events, however
2616 $marc->insert_grouped_field( MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) );
2621 =head2 _koha_modify_biblio
2623 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2625 Internal function for updating the biblio table
2629 sub _koha_modify_biblio {
2630 my ( $dbh, $biblio, $frameworkcode ) = @_;
2635 SET frameworkcode = ?,
2648 WHERE biblionumber = ?
2651 my $sth = $dbh->prepare($query);
2654 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'subtitle'},
2655 $biblio->{'medium'}, $biblio->{'part_number'}, $biblio->{'part_name'}, $biblio->{'unititle'},
2656 $biblio->{'notes'}, $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'} ? int($biblio->{'copyrightdate'}) : undef,
2657 $biblio->{'abstract'}, $biblio->{'biblionumber'}
2658 ) if $biblio->{'biblionumber'};
2660 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
2661 $error .= "ERROR in _koha_modify_biblio $query" . $dbh->errstr;
2664 return ( $biblio->{'biblionumber'}, $error );
2667 =head2 _koha_modify_biblioitem_nonmarc
2669 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
2673 sub _koha_modify_biblioitem_nonmarc {
2674 my ( $dbh, $biblioitem ) = @_;
2677 # re-calculate the cn_sort, it may have changed
2678 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2680 my $query = "UPDATE biblioitems
2681 SET biblionumber = ?,
2687 publicationyear = ?,
2691 collectiontitle = ?,
2693 collectionvolume= ?,
2694 editionstatement= ?,
2695 editionresponsibility = ?,
2711 where biblioitemnumber = ?
2713 my $sth = $dbh->prepare($query);
2715 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
2716 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
2717 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
2718 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
2719 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
2720 $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'},
2721 $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'},
2722 $biblioitem->{'ean'}, $biblioitem->{'agerestriction'}, $biblioitem->{'biblioitemnumber'}
2724 if ( $dbh->errstr ) {
2725 $error .= "ERROR in _koha_modify_biblioitem_nonmarc $query" . $dbh->errstr;
2728 return ( $biblioitem->{'biblioitemnumber'}, $error );
2731 =head2 _koha_delete_biblio
2733 $error = _koha_delete_biblio($dbh,$biblionumber);
2735 Internal sub for deleting from biblio table -- also saves to deletedbiblio
2737 C<$dbh> - the database handle
2739 C<$biblionumber> - the biblionumber of the biblio to be deleted
2743 # FIXME: add error handling
2745 sub _koha_delete_biblio {
2746 my ( $dbh, $biblionumber ) = @_;
2748 # get all the data for this biblio
2749 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
2750 $sth->execute($biblionumber);
2752 # FIXME There is a transaction in _koha_delete_biblio_metadata
2753 # But actually all the following should be done inside a single transaction
2754 if ( my $data = $sth->fetchrow_hashref ) {
2756 # save the record in deletedbiblio
2757 # find the fields to save
2758 my $query = "INSERT INTO deletedbiblio SET ";
2760 foreach my $temp ( keys %$data ) {
2761 $query .= "$temp = ?,";
2762 push( @bind, $data->{$temp} );
2765 # replace the last , by ",?)"
2767 my $bkup_sth = $dbh->prepare($query);
2768 $bkup_sth->execute(@bind);
2771 _koha_delete_biblio_metadata( $biblionumber );
2774 my $sth2 = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
2775 $sth2->execute($biblionumber);
2776 # update the timestamp (Bugzilla 7146)
2777 $sth2= $dbh->prepare("UPDATE deletedbiblio SET timestamp=NOW() WHERE biblionumber=?");
2778 $sth2->execute($biblionumber);
2785 =head2 _koha_delete_biblioitems
2787 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
2789 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
2791 C<$dbh> - the database handle
2792 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
2796 # FIXME: add error handling
2798 sub _koha_delete_biblioitems {
2799 my ( $dbh, $biblioitemnumber ) = @_;
2801 # get all the data for this biblioitem
2802 my $sth = $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
2803 $sth->execute($biblioitemnumber);
2805 if ( my $data = $sth->fetchrow_hashref ) {
2807 # save the record in deletedbiblioitems
2808 # find the fields to save
2809 my $query = "INSERT INTO deletedbiblioitems SET ";
2811 foreach my $temp ( keys %$data ) {
2812 $query .= "$temp = ?,";
2813 push( @bind, $data->{$temp} );
2816 # replace the last , by ",?)"
2818 my $bkup_sth = $dbh->prepare($query);
2819 $bkup_sth->execute(@bind);
2822 # delete the biblioitem
2823 my $sth2 = $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
2824 $sth2->execute($biblioitemnumber);
2825 # update the timestamp (Bugzilla 7146)
2826 $sth2= $dbh->prepare("UPDATE deletedbiblioitems SET timestamp=NOW() WHERE biblioitemnumber=?");
2827 $sth2->execute($biblioitemnumber);
2834 =head2 _koha_delete_biblio_metadata
2836 $error = _koha_delete_biblio_metadata($biblionumber);
2838 C<$biblionumber> - the biblionumber of the biblio metadata to be deleted
2842 sub _koha_delete_biblio_metadata {
2843 my ($biblionumber) = @_;
2845 my $dbh = C4::Context->dbh;
2846 my $schema = Koha::Database->new->schema;
2850 INSERT INTO deletedbiblio_metadata (biblionumber, format, `schema`, metadata)
2851 SELECT biblionumber, format, `schema`, metadata FROM biblio_metadata WHERE biblionumber=?
2852 |, undef, $biblionumber );
2853 $dbh->do( q|DELETE FROM biblio_metadata WHERE biblionumber=?|,
2854 undef, $biblionumber );
2859 =head1 UNEXPORTED FUNCTIONS
2861 =head2 ModBiblioMarc
2863 ModBiblioMarc($newrec,$biblionumber);
2865 Add MARC XML data for a biblio to koha
2867 Function exported, but should NOT be used, unless you really know what you're doing
2872 # pass the MARC::Record to this function, and it will create the records in
2874 my ( $record, $biblionumber ) = @_;
2876 carp 'ModBiblioMarc passed an undefined record';
2880 # Clone record as it gets modified
2881 $record = $record->clone();
2882 my $dbh = C4::Context->dbh;
2883 my @fields = $record->fields();
2884 my $encoding = C4::Context->preference("marcflavour");
2886 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
2887 if ( $encoding eq "UNIMARC" ) {
2888 my $defaultlanguage = C4::Context->preference("UNIMARCField100Language");
2889 $defaultlanguage = "fre" if (!$defaultlanguage || length($defaultlanguage) != 3);
2890 my $string = $record->subfield( 100, "a" );
2891 if ( ($string) && ( length( $record->subfield( 100, "a" ) ) == 36 ) ) {
2892 my $f100 = $record->field(100);
2893 $record->delete_field($f100);
2895 $string = POSIX::strftime( "%Y%m%d", localtime );
2897 $string = sprintf( "%-*s", 35, $string );
2898 substr ( $string, 22, 3, $defaultlanguage);
2900 substr( $string, 25, 3, "y50" );
2901 unless ( $record->subfield( 100, "a" ) ) {
2902 $record->insert_fields_ordered( MARC::Field->new( 100, "", "", "a" => $string ) );
2906 #enhancement 5374: update transaction date (005) for marc21/unimarc
2907 if($encoding =~ /MARC21|UNIMARC/) {
2908 my @a= (localtime) [5,4,3,2,1,0]; $a[0]+=1900; $a[1]++;
2909 # YY MM DD HH MM SS (update year and month)
2910 my $f005= $record->field('005');
2911 $f005->update(sprintf("%4d%02d%02d%02d%02d%04.1f",@a)) if $f005;
2915 biblionumber => $biblionumber,
2916 format => 'marcxml',
2917 schema => C4::Context->preference('marcflavour'),
2919 $record->as_usmarc; # Bug 20126/10455 This triggers field length calculation
2921 my $m_rs = Koha::Biblio::Metadatas->find($metadata) //
2922 Koha::Biblio::Metadata->new($metadata);
2924 my $userenv = C4::Context->userenv;
2926 my $borrowernumber = $userenv->{number};
2927 my $borrowername = join ' ', map { $_ // q{} } @$userenv{qw(firstname surname)};
2928 unless ($m_rs->in_storage) {
2929 Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForCreatorId'), $borrowernumber);
2930 Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForCreatorName'), $borrowername);
2932 Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForModifierId'), $borrowernumber);
2933 Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForModifierName'), $borrowername);
2936 $m_rs->metadata( $record->as_xml_record($encoding) );
2939 my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX });
2940 $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" );
2942 return $biblionumber;
2945 =head2 prepare_host_field
2947 $marcfield = prepare_host_field( $hostbiblioitem, $marcflavour );
2948 Generate the host item entry for an analytic child entry
2952 sub prepare_host_field {
2953 my ( $hostbiblio, $marcflavour ) = @_;
2954 $marcflavour ||= C4::Context->preference('marcflavour');
2955 my $host = GetMarcBiblio({ biblionumber => $hostbiblio });
2956 # unfortunately as_string does not 'do the right thing'
2957 # if field returns undef
2961 if ( $marcflavour eq 'MARC21' ) {
2962 if ( $field = $host->field('100') || $host->field('110') || $host->field('11') ) {
2963 my $s = $field->as_string('ab');
2968 if ( $field = $host->field('245') ) {
2969 my $s = $field->as_string('a');
2974 if ( $field = $host->field('260') ) {
2975 my $s = $field->as_string('abc');
2980 if ( $field = $host->field('240') ) {
2981 my $s = $field->as_string();
2986 if ( $field = $host->field('022') ) {
2987 my $s = $field->as_string('a');
2992 if ( $field = $host->field('020') ) {
2993 my $s = $field->as_string('a');
2998 if ( $field = $host->field('001') ) {
2999 $sfd{w} = $field->data(),;
3001 $host_field = MARC::Field->new( 773, '0', ' ', %sfd );
3004 elsif ( $marcflavour eq 'UNIMARC' ) {
3006 if ( $field = $host->field('700') || $host->field('710') || $host->field('720') ) {
3007 my $s = $field->as_string('ab');
3013 if ( $field = $host->field('200') ) {
3014 my $s = $field->as_string('a');
3019 #place of publicaton
3020 if ( $field = $host->field('210') ) {
3021 my $s = $field->as_string('a');
3026 #date of publication
3027 if ( $field = $host->field('210') ) {
3028 my $s = $field->as_string('d');
3034 if ( $field = $host->field('205') ) {
3035 my $s = $field->as_string();
3041 if ( $field = $host->field('856') ) {
3042 my $s = $field->as_string('u');
3048 if ( $field = $host->field('011') ) {
3049 my $s = $field->as_string('a');
3055 if ( $field = $host->field('010') ) {
3056 my $s = $field->as_string('a');
3061 if ( $field = $host->field('001') ) {
3062 $sfd{0} = $field->data(),;
3064 $host_field = MARC::Field->new( 461, '0', ' ', %sfd );
3071 =head2 UpdateTotalIssues
3073 UpdateTotalIssues($biblionumber, $increase, [$value])
3075 Update the total issue count for a particular bib record.
3079 =item C<$biblionumber> is the biblionumber of the bib to update
3081 =item C<$increase> is the amount to increase (or decrease) the total issues count by
3083 =item C<$value> is the absolute value that total issues count should be set to. If provided, C<$increase> is ignored.
3089 sub UpdateTotalIssues {
3090 my ($biblionumber, $increase, $value, $skip_holds_queue) = @_;
3093 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
3095 carp "UpdateTotalIssues could not get biblio record";
3098 my $biblio = Koha::Biblios->find( $biblionumber );
3100 carp "UpdateTotalIssues could not get datas of biblio";
3103 my $biblioitem = $biblio->biblioitem;
3104 my ($totalissuestag, $totalissuessubfield) = GetMarcFromKohaField( 'biblioitems.totalissues' );
3105 unless ($totalissuestag) {
3106 return 1; # There is nothing to do
3109 if (defined $value) {
3110 $totalissues = $value;
3112 $totalissues = $biblioitem->totalissues + $increase;
3115 my $field = $record->field($totalissuestag);
3116 if (defined $field) {
3117 $field->update( $totalissuessubfield => $totalissues );
3119 $field = MARC::Field->new($totalissuestag, '0', '0',
3120 $totalissuessubfield => $totalissues);
3121 $record->insert_grouped_field($field);
3124 return ModBiblio($record, $biblionumber, $biblio->frameworkcode, { skip_holds_queue => $skip_holds_queue });
3129 &RemoveAllNsb($record);
3131 Removes all nsb/nse chars from a record
3138 carp 'RemoveAllNsb called with undefined record';
3142 SetUTF8Flag($record);
3144 foreach my $field ($record->fields()) {
3145 if ($field->is_control_field()) {
3146 $field->update(nsb_clean($field->data()));
3148 my @subfields = $field->subfields();
3150 foreach my $subfield (@subfields) {
3151 push @new_subfields, $subfield->[0] => nsb_clean($subfield->[1]);
3153 if (scalar(@new_subfields) > 0) {
3156 $new_field = MARC::Field->new(
3158 $field->indicator(1),
3159 $field->indicator(2),
3164 warn "error in RemoveAllNsb : $@";
3166 $field->replace_with($new_field);
3175 =head2 ApplyMarcOverlayRules
3177 my $record = ApplyMarcOverlayRules($params)
3179 Applies marc merge rules to a record.
3181 C<$params> is expected to be a hashref with below keys defined.
3185 =item C<biblionumber>
3186 biblionumber of old record
3189 Incoming record that will be merged with old record
3191 =item C<overlay_context>
3192 hashref containing at least one context module and filter value on
3193 the form {module => filter, ...}.
3203 Merged MARC record based with merge rules for C<context> applied. If no old
3204 record for C<biblionumber> can be found, C<record> is returned unchanged.
3205 Default action when no matching context is found to return C<record> unchanged.
3206 If no rules are found for a certain field tag the default is to overwrite with
3207 fields with this field tag from C<record>.
3213 sub ApplyMarcOverlayRules {
3215 my $biblionumber = $params->{biblionumber};
3216 my $incoming_record = $params->{record};
3218 if (!$biblionumber) {
3219 carp 'ApplyMarcOverlayRules called on undefined biblionumber';
3222 if (!$incoming_record) {
3223 carp 'ApplyMarcOverlayRules called on undefined record';
3226 my $old_record = GetMarcBiblio({ biblionumber => $biblionumber });
3228 # Skip overlay rules if called with no context
3229 if ($old_record && defined $params->{overlay_context}) {
3230 return Koha::MarcOverlayRules->merge_records($old_record, $incoming_record, $params->{overlay_context});
3232 return $incoming_record;
3235 =head2 _after_biblio_action_hooks
3237 Helper method that takes care of calling all plugin hooks
3241 sub _after_biblio_action_hooks {
3244 my $biblio_id = $args->{biblio_id};
3245 my $action = $args->{action};
3247 my $biblio = Koha::Biblios->find( $biblio_id );
3248 Koha::Plugins->call(
3249 'after_biblio_action',
3253 biblio_id => $biblio_id,
3264 Koha Development Team <http://koha-community.org/>
3266 Paul POULAIN paul.poulain@free.fr
3268 Joshua Ferraro jmf@liblime.com