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);
48 GetAuthorisedValueDesc
50 IsMarcStructureInternal
52 GetMarcSubfieldStructureFromKohaField
64 LinkBibHeadingsToAuthorities
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 ;-)
83 use Encode qw( decode is_utf8 );
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; # logaction
101 use Koha::Authority::Types;
102 use Koha::Acquisition::Currencies;
103 use Koha::Biblio::Metadatas;
107 use Koha::SearchEngine;
109 use Koha::Util::MARC;
111 use vars qw($debug $cgi_debug);
116 C4::Biblio - cataloging management functions
120 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:
124 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
126 =item 2. as raw MARC in the Zebra index and storage engine
128 =item 3. as MARC XML in biblio_metadata.metadata
132 In the 3.0 version of Koha, the authoritative record-level information is in biblio_metadata.metadata
134 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.
138 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
140 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
144 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:
148 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
150 =item 2. _koha_* - low-level internal functions for managing the koha tables
152 =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.
154 =item 4. Zebra functions used to update the Zebra index
156 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
160 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 :
164 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
166 =item 2. add the biblionumber and biblioitemnumber into the MARC records
168 =item 3. save the marc record
172 =head1 EXPORTED FUNCTIONS
176 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
178 Exported function (core API) for adding a new biblio to koha.
180 The first argument is a C<MARC::Record> object containing the
181 bib to add, while the second argument is the desired MARC
184 This function also accepts a third, optional argument: a hashref
185 to additional options. The only defined option is C<defer_marc_save>,
186 which if present and mapped to a true value, causes C<AddBiblio>
187 to omit the call to save the MARC in C<biblio_metadata.metadata>
188 This option is provided B<only>
189 for the use of scripts such as C<bulkmarcimport.pl> that may need
190 to do some manipulation of the MARC record for item parsing before
191 saving it and which cannot afford the performance hit of saving
192 the MARC record twice. Consequently, do not use that option
193 unless you can guarantee that C<ModBiblioMarc> will be called.
199 my $frameworkcode = shift;
200 my $options = @_ ? shift : undef;
201 my $defer_marc_save = 0;
203 carp('AddBiblio called with undefined record');
206 if ( defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'} ) {
207 $defer_marc_save = 1;
210 my $schema = Koha::Database->schema;
211 my ( $biblionumber, $biblioitemnumber );
213 $schema->txn_do(sub {
215 if (C4::Context->preference('BiblioAddsAuthorities')) {
216 BiblioAutoLink( $record, $frameworkcode );
219 # transform the data into koha-table style data
220 SetUTF8Flag($record);
221 my $olddata = TransformMarcToKoha( $record, $frameworkcode );
223 my $biblio = Koha::Biblio->new(
225 frameworkcode => $frameworkcode,
226 author => $olddata->{author},
227 title => $olddata->{title},
228 subtitle => $olddata->{subtitle},
229 medium => $olddata->{medium},
230 part_number => $olddata->{part_number},
231 part_name => $olddata->{part_name},
232 unititle => $olddata->{unititle},
233 notes => $olddata->{notes},
235 ( $olddata->{serial} || $olddata->{seriestitle} ? 1 : 0 ),
236 seriestitle => $olddata->{seriestitle},
237 copyrightdate => $olddata->{copyrightdate},
238 datecreated => \'NOW()',
239 abstract => $olddata->{abstract},
242 $biblionumber = $biblio->biblionumber;
243 Koha::Exceptions::ObjectNotCreated->throw unless $biblio;
245 my ($cn_sort) = GetClassSort( $olddata->{'biblioitems.cn_source'}, $olddata->{'cn_class'}, $olddata->{'cn_item'} );
246 my $biblioitem = Koha::Biblioitem->new(
248 biblionumber => $biblionumber,
249 volume => $olddata->{volume},
250 number => $olddata->{number},
251 itemtype => $olddata->{itemtype},
252 isbn => $olddata->{isbn},
253 issn => $olddata->{issn},
254 publicationyear => $olddata->{publicationyear},
255 publishercode => $olddata->{publishercode},
256 volumedate => $olddata->{volumedate},
257 volumedesc => $olddata->{volumedesc},
258 collectiontitle => $olddata->{collectiontitle},
259 collectionissn => $olddata->{collectionissn},
260 collectionvolume => $olddata->{collectionvolume},
261 editionstatement => $olddata->{editionstatement},
262 editionresponsibility => $olddata->{editionresponsibility},
263 illus => $olddata->{illus},
264 pages => $olddata->{pages},
265 notes => $olddata->{bnotes},
266 size => $olddata->{size},
267 place => $olddata->{place},
268 lccn => $olddata->{lccn},
269 url => $olddata->{url},
270 cn_source => $olddata->{'biblioitems.cn_source'},
271 cn_class => $olddata->{cn_class},
272 cn_item => $olddata->{cn_item},
273 cn_suffix => $olddata->{cn_suff},
275 totalissues => $olddata->{totalissues},
276 ean => $olddata->{ean},
277 agerestriction => $olddata->{agerestriction},
280 Koha::Exceptions::ObjectNotCreated->throw unless $biblioitem;
281 $biblioitemnumber = $biblioitem->biblioitemnumber;
283 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
285 # update MARC subfield that stores biblioitems.cn_sort
286 _koha_marc_update_biblioitem_cn_sort( $record, $olddata, $frameworkcode );
289 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
291 # update OAI-PMH sets
292 if(C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
293 C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
296 _after_biblio_action_hooks({ action => 'create', biblio_id => $biblionumber });
298 logaction( "CATALOGUING", "ADD", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
302 ( $biblionumber, $biblioitemnumber ) = ( undef, undef );
304 return ( $biblionumber, $biblioitemnumber );
309 ModBiblio( $record,$biblionumber,$frameworkcode, $disable_autolink);
311 Replace an existing bib record identified by C<$biblionumber>
312 with one supplied by the MARC::Record object C<$record>. The embedded
313 item, biblioitem, and biblionumber fields from the previous
314 version of the bib record replace any such fields of those tags that
315 are present in C<$record>. Consequently, ModBiblio() is not
316 to be used to try to modify item records.
318 C<$frameworkcode> specifies the MARC framework to use
319 when storing the modified bib record; among other things,
320 this controls how MARC fields get mapped to display columns
321 in the C<biblio> and C<biblioitems> tables, as well as
322 which fields are used to store embedded item, biblioitem,
323 and biblionumber data for indexing.
325 Unless C<$disable_autolink> is passed ModBiblio will relink record headings
326 to authorities based on settings in the system preferences. This flag allows
327 us to not relink records when the authority linker is saving modifications.
329 Returns 1 on success 0 on failure
334 my ( $record, $biblionumber, $frameworkcode, $disable_autolink ) = @_;
336 carp 'No record passed to ModBiblio';
340 if ( C4::Context->preference("CataloguingLog") ) {
341 my $newrecord = GetMarcBiblio({ biblionumber => $biblionumber });
342 logaction( "CATALOGUING", "MODIFY", $biblionumber, "biblio BEFORE=>" . $newrecord->as_formatted );
345 if ( !$disable_autolink && C4::Context->preference('BiblioAddsAuthorities') ) {
346 BiblioAutoLink( $record, $frameworkcode );
349 # Cleaning up invalid fields must be done early or SetUTF8Flag is liable to
350 # throw an exception which probably won't be handled.
351 foreach my $field ($record->fields()) {
352 if (! $field->is_control_field()) {
353 if (scalar($field->subfields()) == 0 || (scalar($field->subfields()) == 1 && $field->subfield('9'))) {
354 $record->delete_field($field);
359 SetUTF8Flag($record);
360 my $dbh = C4::Context->dbh;
362 $frameworkcode = "" if !$frameworkcode || $frameworkcode eq "Default"; # XXX
364 _strip_item_fields($record, $frameworkcode);
366 # update biblionumber and biblioitemnumber in MARC
367 # FIXME - this is assuming a 1 to 1 relationship between
368 # biblios and biblioitems
369 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
370 $sth->execute($biblionumber);
371 my ($biblioitemnumber) = $sth->fetchrow;
373 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
375 # load the koha-table data object
376 my $oldbiblio = TransformMarcToKoha( $record, $frameworkcode );
378 # update MARC subfield that stores biblioitems.cn_sort
379 _koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode );
381 # update the MARC record (that now contains biblio and items) with the new record data
382 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
384 # modify the other koha tables
385 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
386 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
388 _after_biblio_action_hooks({ action => 'modify', biblio_id => $biblionumber });
390 # update OAI-PMH sets
391 if(C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
392 C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
398 =head2 _strip_item_fields
400 _strip_item_fields($record, $frameworkcode)
402 Utility routine to remove item tags from a
407 sub _strip_item_fields {
409 my $frameworkcode = shift;
410 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
411 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" );
413 # delete any item fields from incoming record to avoid
414 # duplication or incorrect data - use AddItem() or ModItem()
416 foreach my $field ( $record->field($itemtag) ) {
417 $record->delete_field($field);
423 my $error = &DelBiblio($biblionumber);
425 Exported function (core API) for deleting a biblio in koha.
426 Deletes biblio record from Zebra and Koha tables (biblio & biblioitems)
427 Also backs it up to deleted* tables.
428 Checks to make sure that the biblio has no items attached.
430 C<$error> : undef unless an error occurs
435 my ($biblionumber) = @_;
437 my $biblio = Koha::Biblios->find( $biblionumber );
438 return unless $biblio; # Should we throw an exception instead?
440 my $dbh = C4::Context->dbh;
441 my $error; # for error handling
443 # First make sure this biblio has no items attached
444 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
445 $sth->execute($biblionumber);
446 if ( my $itemnumber = $sth->fetchrow ) {
448 # Fix this to use a status the template can understand
449 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
452 return $error if $error;
454 # We delete attached subscriptions
456 my $subscriptions = C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
457 foreach my $subscription (@$subscriptions) {
458 C4::Serials::DelSubscription( $subscription->{subscriptionid} );
461 # We delete any existing holds
462 my $holds = $biblio->holds;
463 while ( my $hold = $holds->next ) {
467 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
468 # for at least 2 reasons :
469 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
470 # and we would have no way to remove it (except manually in zebra, but I bet it would be very hard to handle the problem)
471 ModZebra( $biblionumber, "recordDelete", "biblioserver" );
473 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
474 $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
475 $sth->execute($biblionumber);
476 while ( my $biblioitemnumber = $sth->fetchrow ) {
478 # delete this biblioitem
479 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
480 return $error if $error;
484 # delete biblio from Koha tables and save in deletedbiblio
485 # must do this *after* _koha_delete_biblioitems, otherwise
486 # delete cascade will prevent deletedbiblioitems rows
487 # from being generated by _koha_delete_biblioitems
488 $error = _koha_delete_biblio( $dbh, $biblionumber );
490 _after_biblio_action_hooks({ action => 'delete', biblio_id => $biblionumber });
492 logaction( "CATALOGUING", "DELETE", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
498 =head2 BiblioAutoLink
500 my $headings_linked = BiblioAutoLink($record, $frameworkcode)
502 Automatically links headings in a bib record to authorities.
504 Returns the number of headings changed
510 my $frameworkcode = shift;
512 carp('Undefined record passed to BiblioAutoLink');
515 my ( $num_headings_changed, %results );
518 "C4::Linker::" . ( C4::Context->preference("LinkerModule") || 'Default' );
519 unless ( can_load( modules => { $linker_module => undef } ) ) {
520 $linker_module = 'C4::Linker::Default';
521 unless ( can_load( modules => { $linker_module => undef } ) ) {
526 my $linker = $linker_module->new(
527 { 'options' => C4::Context->preference("LinkerOptions") } );
528 my ( $headings_changed, undef ) =
529 LinkBibHeadingsToAuthorities( $linker, $record, $frameworkcode, C4::Context->preference("CatalogModuleRelink") || '' );
530 # By default we probably don't want to relink things when cataloging
531 return $headings_changed;
534 =head2 LinkBibHeadingsToAuthorities
536 my $num_headings_changed, %results = LinkBibHeadingsToAuthorities($linker, $marc, $frameworkcode, [$allowrelink]);
538 Links bib headings to authority records by checking
539 each authority-controlled field in the C<MARC::Record>
540 object C<$marc>, looking for a matching authority record,
541 and setting the linking subfield $9 to the ID of that
544 If $allowrelink is false, existing authids will never be
545 replaced, regardless of the values of LinkerKeepStale and
548 Returns the number of heading links changed in the
553 sub LinkBibHeadingsToAuthorities {
556 my $frameworkcode = shift;
557 my $allowrelink = shift;
560 carp 'LinkBibHeadingsToAuthorities called on undefined bib record';
564 require C4::AuthoritiesMarc;
566 $allowrelink = 1 unless defined $allowrelink;
567 my $num_headings_changed = 0;
568 foreach my $field ( $bib->fields() ) {
569 my $heading = C4::Heading->new_from_field( $field, $frameworkcode );
570 next unless defined $heading;
573 my $current_link = $field->subfield('9');
575 if ( defined $current_link && (!$allowrelink || !C4::Context->preference('LinkerRelink')) )
577 $results{'linked'}->{ $heading->display_form() }++;
581 my ( $authid, $fuzzy, $match_count ) = $linker->get_link($heading);
583 $results{ $fuzzy ? 'fuzzy' : 'linked' }
584 ->{ $heading->display_form() }++;
585 next if defined $current_link and $current_link == $authid;
587 $field->delete_subfield( code => '9' ) if defined $current_link;
588 $field->add_subfields( '9', $authid );
589 $num_headings_changed++;
592 if ( defined $current_link
593 && (!$allowrelink || C4::Context->preference('LinkerKeepStale')) )
595 $results{'fuzzy'}->{ $heading->display_form() }++;
597 elsif ( C4::Context->preference('AutoCreateAuthorities') ) {
598 if ( _check_valid_auth_link( $current_link, $field ) ) {
599 $results{'linked'}->{ $heading->display_form() }++;
601 elsif ( !$match_count ) {
602 my $authority_type = Koha::Authority::Types->find( $heading->auth_type() );
603 my $marcrecordauth = MARC::Record->new();
604 if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
605 $marcrecordauth->leader(' nz a22 o 4500');
606 SetMarcUnicodeFlag( $marcrecordauth, 'MARC21' );
608 $field->delete_subfield( code => '9' )
609 if defined $current_link;
611 foreach my $subfield ( $field->subfields() ){
612 if ( $subfield->[0] =~ /[A-z]/
613 && C4::Heading::valid_heading_subfield(
614 $field->tag, $subfield->[0] )
616 push @auth_subfields, $subfield->[0] => $subfield->[1];
619 # Bib headings contain some ending punctuation that should NOT
620 # be included in the authority record. Strip those before creation
621 next unless @auth_subfields; # Don't try to create a record if we have no fields;
622 my $last_sub = pop @auth_subfields;
623 $last_sub =~ s/[\s]*[,.:=;!%\/][\s]*$//;
624 push @auth_subfields, $last_sub;
625 my $authfield = MARC::Field->new( $authority_type->auth_tag_to_report, '', '', @auth_subfields );
626 $marcrecordauth->insert_fields_ordered($authfield);
628 # bug 2317: ensure new authority knows it's using UTF-8; currently
629 # only need to do this for MARC21, as MARC::Record->as_xml_record() handles
630 # automatically for UNIMARC (by not transcoding)
631 # FIXME: AddAuthority() instead should simply explicitly require that the MARC::Record
632 # use UTF-8, but as of 2008-08-05, did not want to introduce that kind
633 # of change to a core API just before the 3.0 release.
635 if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
636 my $userenv = C4::Context->userenv;
638 if ( $userenv && $userenv->{'branch'} ) {
639 $library = Koha::Libraries->find( $userenv->{'branch'} );
641 $marcrecordauth->insert_fields_ordered(
644 'a' => "Machine generated authority record."
648 $bib->author() . ", "
649 . $bib->title_proper() . ", "
650 . $bib->publication_date() . " ";
651 $cite =~ s/^[\s\,]*//;
652 $cite =~ s/[\s\,]*$//;
655 . ( $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode') ) . ")"
656 . $bib->subfield( '999', 'c' ) . ": "
658 $marcrecordauth->insert_fields_ordered(
659 MARC::Field->new( '670', '', '', 'a' => $cite ) );
662 # warn "AUTH RECORD ADDED : ".$marcrecordauth->as_formatted;
665 C4::AuthoritiesMarc::AddAuthority( $marcrecordauth, '',
666 $heading->auth_type() );
667 $field->add_subfields( '9', $authid );
668 $num_headings_changed++;
669 $linker->update_cache($heading, $authid);
670 $results{'added'}->{ $heading->display_form() }++;
673 elsif ( defined $current_link ) {
674 if ( _check_valid_auth_link( $current_link, $field ) ) {
675 $results{'linked'}->{ $heading->display_form() }++;
678 $field->delete_subfield( code => '9' );
679 $num_headings_changed++;
680 $results{'unlinked'}->{ $heading->display_form() }++;
684 $results{'unlinked'}->{ $heading->display_form() }++;
689 return $num_headings_changed, \%results;
692 =head2 _check_valid_auth_link
694 if ( _check_valid_auth_link($authid, $field) ) {
698 Check whether the specified heading-auth link is valid without reference
699 to Zebra. Ideally this code would be in C4::Heading, but that won't be
700 possible until we have de-cycled C4::AuthoritiesMarc, so this is the
705 sub _check_valid_auth_link {
706 my ( $authid, $field ) = @_;
707 require C4::AuthoritiesMarc;
709 my $authorized_heading =
710 C4::AuthoritiesMarc::GetAuthorizedHeading( { 'authid' => $authid } ) || '';
711 return ($field->as_string('abcdefghijklmnopqrstuvwxyz') eq $authorized_heading);
716 $data = &GetBiblioData($biblionumber);
718 Returns information about the book with the given biblionumber.
719 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
720 the C<biblio> and C<biblioitems> tables in the
723 In addition, C<$data-E<gt>{subject}> is the list of the book's
724 subjects, separated by C<" , "> (space, comma, space).
725 If there are multiple biblioitems with the given biblionumber, only
726 the first one is considered.
732 my $dbh = C4::Context->dbh;
734 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
736 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
737 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
738 WHERE biblio.biblionumber = ?";
740 my $sth = $dbh->prepare($query);
741 $sth->execute($bibnum);
743 $data = $sth->fetchrow_hashref;
747 } # sub GetBiblioData
751 $isbd = &GetISBDView({
752 'record' => $marc_record,
753 'template' => $interface, # opac/intranet
754 'framework' => $framework,
757 Return the ISBD view which can be included in opac and intranet
764 # Expecting record WITH items.
765 my $record = $params->{record};
766 return unless defined $record;
768 my $template = $params->{template} // q{};
769 my $sysprefname = $template eq 'opac' ? 'opacisbd' : 'isbd';
770 my $framework = $params->{framework};
771 my $itemtype = $framework;
772 my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch" );
773 my $tagslib = GetMarcStructure( 1, $itemtype, { unsafe => 1 } );
775 my $ISBD = C4::Context->preference($sysprefname);
780 foreach my $isbdfield ( split( /#/, $bloc ) ) {
782 # $isbdfield= /(.?.?.?)/;
783 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
784 my $fieldvalue = $1 || 0;
785 my $subfvalue = $2 || "";
787 my $analysestring = $4;
790 # warn "==> $1 / $2 / $3 / $4";
791 # my $fieldvalue=substr($isbdfield,0,3);
792 if ( $fieldvalue > 0 ) {
793 my $hasputtextbefore = 0;
794 my @fieldslist = $record->field($fieldvalue);
795 @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf );
797 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
798 # warn "FV : $fieldvalue";
799 if ( $subfvalue ne "" ) {
800 # OPAC hidden subfield
802 if ( ( $template eq 'opac' )
803 && ( $tagslib->{$fieldvalue}->{$subfvalue}->{'hidden'} || 0 ) > 0 );
804 foreach my $field (@fieldslist) {
805 foreach my $subfield ( $field->subfield($subfvalue) ) {
806 my $calculated = $analysestring;
807 my $tag = $field->tag();
810 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib );
811 my $tagsubf = $tag . $subfvalue;
812 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
813 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
815 # field builded, store the result
816 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
817 $blocres .= $textbefore;
818 $hasputtextbefore = 1;
821 # remove punctuation at start
822 $calculated =~ s/^( |;|:|\.|-)*//g;
823 $blocres .= $calculated;
828 $blocres .= $textafter if $hasputtextbefore;
830 foreach my $field (@fieldslist) {
831 my $calculated = $analysestring;
832 my $tag = $field->tag();
835 my @subf = $field->subfields;
836 for my $i ( 0 .. $#subf ) {
837 my $valuecode = $subf[$i][1];
838 my $subfieldcode = $subf[$i][0];
839 # OPAC hidden subfield
841 if ( ( $template eq 'opac' )
842 && ( $tagslib->{$fieldvalue}->{$subfieldcode}->{'hidden'} || 0 ) > 0 );
843 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib );
844 my $tagsubf = $tag . $subfieldcode;
846 $calculated =~ s/ # replace all {{}} codes by the value code.
847 \{\{$tagsubf\}\} # catch the {{actualcode}}
849 $valuecode # replace by the value code
852 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
853 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
856 # field builded, store the result
857 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
858 $blocres .= $textbefore;
859 $hasputtextbefore = 1;
862 # remove punctuation at start
863 $calculated =~ s/^( |;|:|\.|-)*//g;
864 $blocres .= $calculated;
867 $blocres .= $textafter if $hasputtextbefore;
870 $blocres .= $isbdfield;
875 $res =~ s/\{(.*?)\}//g;
877 $res =~ s/\n/<br\/>/g;
885 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
887 =head2 IsMarcStructureInternal
889 my $tagslib = C4::Biblio::GetMarcStructure();
890 for my $tag ( sort keys %$tagslib ) {
892 for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
893 next if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
898 GetMarcStructure creates keys (lib, tab, mandatory, repeatable) for a display purpose.
899 These different values should not be processed as valid subfields.
903 sub IsMarcStructureInternal {
904 my ( $subfield ) = @_;
905 return ref $subfield ? 0 : 1;
908 =head2 GetMarcStructure
910 $res = GetMarcStructure($forlibrarian, $frameworkcode, [ $params ]);
912 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
913 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
914 $frameworkcode : the framework code to read
915 $params allows you to pass { unsafe => 1 } for better performance.
917 Note: If you call GetMarcStructure with unsafe => 1, do not modify or
918 even autovivify its contents. It is a cached/shared data structure. Your
919 changes c/would be passed around in subsequent calls.
923 sub GetMarcStructure {
924 my ( $forlibrarian, $frameworkcode, $params ) = @_;
925 $frameworkcode = "" unless $frameworkcode;
927 $forlibrarian = $forlibrarian ? 1 : 0;
928 my $unsafe = ($params && $params->{unsafe})? 1: 0;
929 my $cache = Koha::Caches->get_instance();
930 my $cache_key = "MarcStructure-$forlibrarian-$frameworkcode";
931 my $cached = $cache->get_from_cache($cache_key, { unsafe => $unsafe });
932 return $cached if $cached;
934 my $dbh = C4::Context->dbh;
935 my $sth = $dbh->prepare(
936 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable,ind1_defaultvalue,ind2_defaultvalue
937 FROM marc_tag_structure
938 WHERE frameworkcode=?
941 $sth->execute($frameworkcode);
942 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable, $ind1_defaultvalue, $ind2_defaultvalue );
944 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable, $ind1_defaultvalue, $ind2_defaultvalue ) = $sth->fetchrow ) {
945 $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
946 $res->{$tag}->{tab} = "";
947 $res->{$tag}->{mandatory} = $mandatory;
948 $res->{$tag}->{repeatable} = $repeatable;
949 $res->{$tag}->{ind1_defaultvalue} = $ind1_defaultvalue;
950 $res->{$tag}->{ind2_defaultvalue} = $ind2_defaultvalue;
953 $sth = $dbh->prepare(
954 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue,maxlength
955 FROM marc_subfield_structure
956 WHERE frameworkcode=?
957 ORDER BY tagfield,tagsubfield
961 $sth->execute($frameworkcode);
964 my $authorised_value;
976 ( $tag, $subfield, $liblibrarian, $libopac, $tab, $mandatory, $repeatable, $authorised_value,
977 $authtypecode, $value_builder, $kohafield, $seealso, $hidden, $isurl, $link, $defaultvalue,
982 $res->{$tag}->{$subfield}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
983 $res->{$tag}->{$subfield}->{tab} = $tab;
984 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
985 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
986 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
987 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
988 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
989 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
990 $res->{$tag}->{$subfield}->{seealso} = $seealso;
991 $res->{$tag}->{$subfield}->{hidden} = $hidden;
992 $res->{$tag}->{$subfield}->{isurl} = $isurl;
993 $res->{$tag}->{$subfield}->{'link'} = $link;
994 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
995 $res->{$tag}->{$subfield}->{maxlength} = $maxlength;
998 $cache->set_in_cache($cache_key, $res);
1002 =head2 GetUsedMarcStructure
1004 The same function as GetMarcStructure except it just takes field
1005 in tab 0-9. (used field)
1007 my $results = GetUsedMarcStructure($frameworkcode);
1009 C<$results> is a ref to an array which each case contains a ref
1010 to a hash which each keys is the columns from marc_subfield_structure
1012 C<$frameworkcode> is the framework code.
1016 sub GetUsedMarcStructure {
1017 my $frameworkcode = shift || '';
1020 FROM marc_subfield_structure
1022 AND frameworkcode = ?
1023 ORDER BY tagfield, tagsubfield
1025 my $sth = C4::Context->dbh->prepare($query);
1026 $sth->execute($frameworkcode);
1027 return $sth->fetchall_arrayref( {} );
1032 =head2 GetMarcSubfieldStructure
1034 my $structure = GetMarcSubfieldStructure($frameworkcode, [$params]);
1036 Returns a reference to hash representing MARC subfield structure
1037 for framework with framework code C<$frameworkcode>, C<$params> is
1038 optional and may contain additional options.
1042 =item C<$frameworkcode>
1048 An optional hash reference with additional options.
1049 The following options are supported:
1055 Pass { unsafe => 1 } do disable cached object cloning,
1056 and instead get a shared reference, resulting in better
1057 performance (but care must be taken so that retured object
1060 Note: If you call GetMarcSubfieldStructure with unsafe => 1, do not modify or
1061 even autovivify its contents. It is a cached/shared data structure. Your
1062 changes would be passed around in subsequent calls.
1070 sub GetMarcSubfieldStructure {
1071 my ( $frameworkcode, $params ) = @_;
1073 $frameworkcode //= '';
1075 my $cache = Koha::Caches->get_instance();
1076 my $cache_key = "MarcSubfieldStructure-$frameworkcode";
1077 my $cached = $cache->get_from_cache($cache_key, { unsafe => ($params && $params->{unsafe}) });
1078 return $cached if $cached;
1080 my $dbh = C4::Context->dbh;
1081 # We moved to selectall_arrayref since selectall_hashref does not
1082 # keep duplicate mappings on kohafield (like place in 260 vs 264)
1083 my $subfield_aref = $dbh->selectall_arrayref( q|
1085 FROM marc_subfield_structure
1086 WHERE frameworkcode = ?
1088 ORDER BY frameworkcode,tagfield,tagsubfield
1089 |, { Slice => {} }, $frameworkcode );
1090 # Now map the output to a hash structure
1091 my $subfield_structure = {};
1092 foreach my $row ( @$subfield_aref ) {
1093 push @{ $subfield_structure->{ $row->{kohafield} }}, $row;
1095 $cache->set_in_cache( $cache_key, $subfield_structure );
1096 return $subfield_structure;
1099 =head2 GetMarcFromKohaField
1101 ( $field,$subfield ) = GetMarcFromKohaField( $kohafield );
1102 @fields = GetMarcFromKohaField( $kohafield );
1103 $field = GetMarcFromKohaField( $kohafield );
1105 Returns the MARC fields & subfields mapped to $kohafield.
1106 Since the Default framework is considered as authoritative for such
1107 mappings, the former frameworkcode parameter is obsoleted.
1109 In list context all mappings are returned; there can be multiple
1110 mappings. Note that in the above example you could miss a second
1111 mappings in the first call.
1112 In scalar context only the field tag of the first mapping is returned.
1116 sub GetMarcFromKohaField {
1117 my ( $kohafield ) = @_;
1118 return unless $kohafield;
1119 # The next call uses the Default framework since it is AUTHORITATIVE
1120 # for all Koha to MARC mappings.
1121 my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework
1123 foreach( @{ $mss->{$kohafield} } ) {
1124 push @retval, $_->{tagfield}, $_->{tagsubfield};
1126 return wantarray ? @retval : ( @retval ? $retval[0] : undef );
1129 =head2 GetMarcSubfieldStructureFromKohaField
1131 my $str = GetMarcSubfieldStructureFromKohaField( $kohafield );
1133 Returns marc subfield structure information for $kohafield.
1134 The Default framework is used, since it is authoritative for kohafield
1136 In list context returns a list of all hashrefs, since there may be
1137 multiple mappings. In scalar context the first hashref is returned.
1141 sub GetMarcSubfieldStructureFromKohaField {
1142 my ( $kohafield ) = @_;
1144 return unless $kohafield;
1146 # The next call uses the Default framework since it is AUTHORITATIVE
1147 # for all Koha to MARC mappings.
1148 my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework
1149 return unless $mss->{$kohafield};
1150 return wantarray ? @{$mss->{$kohafield}} : $mss->{$kohafield}->[0];
1153 =head2 GetMarcBiblio
1155 my $record = GetMarcBiblio({
1156 biblionumber => $biblionumber,
1157 embed_items => $embeditems,
1159 borcat => $patron_category });
1161 Returns MARC::Record representing a biblio record, or C<undef> if the
1162 biblionumber doesn't exist.
1164 Both embed_items and opac are optional.
1165 If embed_items is passed and is 1, items are embedded.
1166 If opac is passed and is 1, the record is filtered as needed.
1170 =item C<$biblionumber>
1174 =item C<$embeditems>
1176 set to true to include item information.
1180 set to true to make the result suited for OPAC view. This causes things like
1181 OpacHiddenItems to be applied.
1185 If the OpacHiddenItemsExceptions system preference is set, this patron category
1186 can be used to make visible OPAC items which would be normally hidden.
1187 It only makes sense in combination both embed_items and opac values true.
1196 if (not defined $params) {
1197 carp 'GetMarcBiblio called without parameters';
1201 my $biblionumber = $params->{biblionumber};
1202 my $embeditems = $params->{embed_items} || 0;
1203 my $opac = $params->{opac} || 0;
1204 my $borcat = $params->{borcat} // q{};
1206 if (not defined $biblionumber) {
1207 carp 'GetMarcBiblio called with undefined biblionumber';
1211 my $dbh = C4::Context->dbh;
1212 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=? ");
1213 $sth->execute($biblionumber);
1214 my $row = $sth->fetchrow_hashref;
1215 my $biblioitemnumber = $row->{'biblioitemnumber'};
1216 my $marcxml = GetXmlBiblio( $biblionumber );
1217 $marcxml = StripNonXmlChars( $marcxml );
1218 my $frameworkcode = GetFrameworkCode($biblionumber);
1219 MARC::File::XML->default_record_format( C4::Context->preference('marcflavour') );
1220 my $record = MARC::Record->new();
1224 MARC::Record::new_from_xml( $marcxml, "UTF-8",
1225 C4::Context->preference('marcflavour') );
1227 if ($@) { warn " problem with :$biblionumber : $@ \n$marcxml"; }
1228 return unless $record;
1230 C4::Biblio::_koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber,
1231 $biblioitemnumber );
1232 C4::Biblio::EmbedItemsInMarcBiblio({
1233 marc_record => $record,
1234 biblionumber => $biblionumber,
1236 borcat => $borcat })
1248 my $marcxml = GetXmlBiblio($biblionumber);
1250 Returns biblio_metadata.metadata/marcxml of the biblionumber passed in parameter.
1251 The XML should only contain biblio information (item information is no longer stored in marcxml field)
1256 my ($biblionumber) = @_;
1257 my $dbh = C4::Context->dbh;
1258 return unless $biblionumber;
1259 my ($marcxml) = $dbh->selectrow_array(
1262 FROM biblio_metadata
1263 WHERE biblionumber=?
1264 AND format='marcxml'
1266 |, undef, $biblionumber, C4::Context->preference('marcflavour')
1273 return the prices in accordance with the Marc format.
1275 returns 0 if no price found
1276 returns undef if called without a marc record or with
1277 an unrecognized marc format
1282 my ( $record, $marcflavour ) = @_;
1284 carp 'GetMarcPrice called on undefined record';
1291 if ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) {
1292 @listtags = ('345', '020');
1294 } elsif ( $marcflavour eq "UNIMARC" ) {
1295 @listtags = ('345', '010');
1301 for my $field ( $record->field(@listtags) ) {
1302 for my $subfield_value ($field->subfield($subfield)){
1304 $subfield_value = MungeMarcPrice( $subfield_value );
1305 return $subfield_value if ($subfield_value);
1308 return 0; # no price found
1311 =head2 MungeMarcPrice
1313 Return the best guess at what the actual price is from a price field.
1317 sub MungeMarcPrice {
1319 return unless ( $price =~ m/\d/ ); ## No digits means no price.
1320 # Look for the currency symbol and the normalized code of the active currency, if it's there,
1321 my $active_currency = Koha::Acquisition::Currencies->get_active;
1322 my $symbol = $active_currency->symbol;
1323 my $isocode = $active_currency->isocode;
1324 $isocode = $active_currency->currency unless defined $isocode;
1327 my @matches =($price=~ /
1329 ( # start of capturing parenthesis
1331 (?:[\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'
1332 |(?:\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'
1334 \s?\p{Sc}?\s? # followed or not by a whitespace. \p{Sc}?\s? are for cases like '25$ USD'
1336 (?:[\p{Sc}\p{L}\/.]){1,4} # followed by same block as symbol block
1337 |(?:\d+[\p{P}\s]?){1,4} # or by same block as digits block
1339 \s?\p{L}{0,4}\s? # followed or not by a whitespace. \p{L}{0,4}\s? are for cases like '$9.50 USD'
1340 ) # end of capturing parenthesis
1341 (?:\p{P}|\z) # followed by a punctuation sign or by the end of the string
1345 foreach ( @matches ) {
1346 $localprice = $_ and last if index($_, $isocode)>=0;
1348 if ( !$localprice ) {
1349 foreach ( @matches ) {
1350 $localprice = $_ and last if $_=~ /(^|[^\p{Sc}\p{L}\/])\Q$symbol\E([^\p{Sc}\p{L}\/]+\z|\z)/;
1355 if ( $localprice ) {
1356 $price = $localprice;
1358 ## Grab the first number in the string ( can use commas or periods for thousands separator and/or decimal separator )
1359 ( $price ) = $price =~ m/([\d\,\.]+[[\,\.]\d\d]?)/;
1361 # eliminate symbol/isocode, space and any final dot from the string
1362 $price =~ s/[\p{Sc}\p{L}\/ ]|\.$//g;
1363 # remove comma,dot when used as separators from hundreds
1364 $price =~s/[\,\.](\d{3})/$1/g;
1365 # convert comma to dot to ensure correct display of decimals if existing
1371 =head2 GetMarcQuantity
1373 return the quantity of a book. Used in acquisition only, when importing a file an iso2709 from a bookseller
1374 Warning : this is not really in the marc standard. In Unimarc, Electre (the most widely used bookseller) use the 969$a
1376 returns 0 if no quantity found
1377 returns undef if called without a marc record or with
1378 an unrecognized marc format
1382 sub GetMarcQuantity {
1383 my ( $record, $marcflavour ) = @_;
1385 carp 'GetMarcQuantity called on undefined record';
1392 if ( $marcflavour eq "MARC21" ) {
1394 } elsif ( $marcflavour eq "UNIMARC" ) {
1395 @listtags = ('969');
1401 for my $field ( $record->field(@listtags) ) {
1402 for my $subfield_value ($field->subfield($subfield)){
1404 if ($subfield_value) {
1405 # in France, the cents separator is the , but sometimes, ppl use a .
1406 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
1407 $subfield_value =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
1408 return $subfield_value;
1412 return 0; # no price found
1416 =head2 GetAuthorisedValueDesc
1418 my $subfieldvalue =get_authorised_value_desc(
1419 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category, $opac);
1421 Retrieve the complete description for a given authorised value.
1423 Now takes $category and $value pair too.
1425 my $auth_value_desc =GetAuthorisedValueDesc(
1426 '','', 'DVD' ,'','','CCODE');
1428 If the optional $opac parameter is set to a true value, displays OPAC
1429 descriptions rather than normal ones when they exist.
1433 sub GetAuthorisedValueDesc {
1434 my ( $tag, $subfield, $value, $framework, $tagslib, $category, $opac ) = @_;
1438 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1441 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1442 my $branch = Koha::Libraries->find($value);
1443 return $branch? $branch->branchname: q{};
1447 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1448 my $itemtype = Koha::ItemTypes->find( $value );
1449 return $itemtype ? $itemtype->translated_description : q||;
1452 #---- "true" authorized value
1453 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1456 my $dbh = C4::Context->dbh;
1457 if ( $category ne "" ) {
1458 my $sth = $dbh->prepare( "SELECT lib, lib_opac FROM authorised_values WHERE category = ? AND authorised_value = ?" );
1459 $sth->execute( $category, $value );
1460 my $data = $sth->fetchrow_hashref;
1461 return ( $opac && $data->{'lib_opac'} ) ? $data->{'lib_opac'} : $data->{'lib'};
1463 return $value; # if nothing is found return the original value
1467 =head2 GetMarcControlnumber
1469 $marccontrolnumber = GetMarcControlnumber($record,$marcflavour);
1471 Get the control number / record Identifier from the MARC record and return it.
1475 sub GetMarcControlnumber {
1476 my ( $record, $marcflavour ) = @_;
1478 carp 'GetMarcControlnumber called on undefined record';
1481 my $controlnumber = "";
1482 # Control number or Record identifier are the same field in MARC21, UNIMARC and NORMARC
1483 # Keep $marcflavour for possible later use
1484 if ($marcflavour eq "MARC21" || $marcflavour eq "UNIMARC" || $marcflavour eq "NORMARC") {
1485 my $controlnumberField = $record->field('001');
1486 if ($controlnumberField) {
1487 $controlnumber = $controlnumberField->data();
1490 return $controlnumber;
1495 $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
1497 Get all ISBNs from the MARC record and returns them in an array.
1498 ISBNs stored in different fields depending on MARC flavour
1503 my ( $record, $marcflavour ) = @_;
1505 carp 'GetMarcISBN called on undefined record';
1509 if ( $marcflavour eq "UNIMARC" ) {
1511 } else { # assume marc21 if not unimarc
1516 foreach my $field ( $record->field($scope) ) {
1517 my $isbn = $field->subfield( 'a' );
1518 if ( $isbn && $isbn ne "" ) {
1519 push @marcisbns, $isbn;
1529 $marcissnsarray = GetMarcISSN( $record, $marcflavour );
1531 Get all valid ISSNs from the MARC record and returns them in an array.
1532 ISSNs are stored in different fields depending on MARC flavour
1537 my ( $record, $marcflavour ) = @_;
1539 carp 'GetMarcISSN called on undefined record';
1543 if ( $marcflavour eq "UNIMARC" ) {
1546 else { # assume MARC21 or NORMARC
1550 foreach my $field ( $record->field($scope) ) {
1551 push @marcissns, $field->subfield( 'a' )
1552 if ( $field->subfield( 'a' ) ne "" );
1559 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1561 Get all notes from the MARC record and returns them in an array.
1562 The notes are stored in different fields depending on MARC flavour.
1563 MARC21 5XX $u subfields receive special attention as they are URIs.
1568 my ( $record, $marcflavour, $opac ) = @_;
1570 carp 'GetMarcNotes called on undefined record';
1574 my $scope = $marcflavour eq "UNIMARC"? '3..': '5..';
1577 #MARC21 specs indicate some notes should be private if first indicator 0
1578 my %maybe_private = (
1586 my %hiddenlist = map { $_ => 1 }
1587 split( /,/, C4::Context->preference('NotesToHide'));
1588 foreach my $field ( $record->field($scope) ) {
1589 my $tag = $field->tag();
1590 next if $hiddenlist{ $tag };
1591 next if $opac && $maybe_private{$tag} && !$field->indicator(1);
1592 if( $marcflavour ne 'UNIMARC' && $field->subfield('u') ) {
1593 # Field 5XX$u always contains URI
1594 # Examples: 505u, 506u, 510u, 514u, 520u, 530u, 538u, 540u, 542u, 552u, 555u, 561u, 563u, 583u
1595 # We first push the other subfields, then all $u's separately
1596 # Leave further actions to the template (see e.g. opac-detail)
1598 join '', ( 'a' .. 't', 'v' .. 'z', '0' .. '9' ); # excl 'u'
1599 push @marcnotes, { marcnote => $field->as_string($othersub) };
1600 foreach my $sub ( $field->subfield('u') ) {
1601 $sub =~ s/^\s+|\s+$//g; # trim
1602 push @marcnotes, { marcnote => $sub };
1605 push @marcnotes, { marcnote => $field->as_string() };
1611 =head2 GetMarcSubjects
1613 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1615 Get all subjects from the MARC record and returns them in an array.
1616 The subjects are stored in different fields depending on MARC flavour
1620 sub GetMarcSubjects {
1621 my ( $record, $marcflavour ) = @_;
1623 carp 'GetMarcSubjects called on undefined record';
1626 my ( $mintag, $maxtag, $fields_filter );
1627 if ( $marcflavour eq "UNIMARC" ) {
1630 $fields_filter = '6..';
1631 } else { # marc21/normarc
1634 $fields_filter = '6..';
1639 my $subject_limit = C4::Context->preference("TraceCompleteSubfields") ? 'su,complete-subfield' : 'su';
1640 my $AuthoritySeparator = C4::Context->preference('AuthoritySeparator');
1642 foreach my $field ( $record->field($fields_filter) ) {
1643 next unless ($field->tag() >= $mintag && $field->tag() <= $maxtag);
1645 my @subfields = $field->subfields();
1648 # if there is an authority link, build the links with an= subfield9
1649 my $subfield9 = $field->subfield('9');
1652 my $linkvalue = $subfield9;
1653 $linkvalue =~ s/(\(|\))//g;
1654 @link_loop = ( { limit => 'an', 'link' => $linkvalue } );
1655 $authoritylink = $linkvalue
1659 for my $subject_subfield (@subfields) {
1660 next if ( $subject_subfield->[0] eq '9' );
1662 # don't load unimarc subfields 3,4,5
1663 next if ( ( $marcflavour eq "UNIMARC" ) and ( $subject_subfield->[0] =~ /2|3|4|5/ ) );
1664 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1665 next if ( ( $marcflavour eq "MARC21" ) and ( $subject_subfield->[0] =~ /2/ ) );
1667 my $code = $subject_subfield->[0];
1668 my $value = $subject_subfield->[1];
1669 my $linkvalue = $value;
1670 $linkvalue =~ s/(\(|\))//g;
1671 # if no authority link, build a search query
1672 unless ($subfield9) {
1674 limit => $subject_limit,
1675 'link' => $linkvalue,
1676 operator => (scalar @link_loop) ? ' and ' : undef
1679 my @this_link_loop = @link_loop;
1681 unless ( $code eq '0' ) {
1682 push @subfields_loop, {
1685 link_loop => \@this_link_loop,
1686 separator => (scalar @subfields_loop) ? $AuthoritySeparator : ''
1691 push @marcsubjects, {
1692 MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop,
1693 authoritylink => $authoritylink,
1694 } if $authoritylink || @subfields_loop;
1697 return \@marcsubjects;
1698 } #end getMARCsubjects
1700 =head2 GetMarcAuthors
1702 authors = GetMarcAuthors($record,$marcflavour);
1704 Get all authors from the MARC record and returns them in an array.
1705 The authors are stored in different fields depending on MARC flavour
1709 sub GetMarcAuthors {
1710 my ( $record, $marcflavour ) = @_;
1712 carp 'GetMarcAuthors called on undefined record';
1715 my ( $mintag, $maxtag, $fields_filter );
1717 # tagslib useful only for UNIMARC author responsibilities
1719 if ( $marcflavour eq "UNIMARC" ) {
1720 # FIXME : we don't have the framework available, we take the default framework. May be buggy on some setups, will be usually correct.
1721 $tagslib = GetMarcStructure( 1, '', { unsafe => 1 });
1724 $fields_filter = '7..';
1725 } else { # marc21/normarc
1728 $fields_filter = '7..';
1732 my $AuthoritySeparator = C4::Context->preference('AuthoritySeparator');
1734 foreach my $field ( $record->field($fields_filter) ) {
1735 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1738 my @subfields = $field->subfields();
1741 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1742 my $subfield9 = $field->subfield('9');
1744 my $linkvalue = $subfield9;
1745 $linkvalue =~ s/(\(|\))//g;
1746 @link_loop = ( { 'limit' => 'an', 'link' => $linkvalue } );
1751 for my $authors_subfield (@subfields) {
1752 next if ( $authors_subfield->[0] eq '9' );
1754 # unimarc3 contains the $3 of the author for UNIMARC.
1755 # For french academic libraries, it's the "ppn", and it's required for idref webservice
1756 $unimarc3 = $authors_subfield->[1] if $marcflavour eq 'UNIMARC' and $authors_subfield->[0] =~ /3/;
1758 # don't load unimarc subfields 3, 5
1759 next if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /3|5/ ) );
1761 my $code = $authors_subfield->[0];
1762 my $value = $authors_subfield->[1];
1763 my $linkvalue = $value;
1764 $linkvalue =~ s/(\(|\))//g;
1765 # UNIMARC author responsibility
1766 if ( $marcflavour eq 'UNIMARC' and $code eq '4' ) {
1767 $value = GetAuthorisedValueDesc( $field->tag(), $code, $value, '', $tagslib );
1768 $linkvalue = "($value)";
1770 # if no authority link, build a search query
1771 unless ($subfield9) {
1774 'link' => $linkvalue,
1775 operator => (scalar @link_loop) ? ' and ' : undef
1778 my @this_link_loop = @link_loop;
1780 unless ( $code eq '0') {
1781 push @subfields_loop, {
1782 tag => $field->tag(),
1785 link_loop => \@this_link_loop,
1786 separator => (scalar @subfields_loop) ? $AuthoritySeparator : ''
1790 push @marcauthors, {
1791 MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop,
1792 authoritylink => $subfield9,
1793 unimarc3 => $unimarc3
1796 return \@marcauthors;
1801 $marcurls = GetMarcUrls($record,$marcflavour);
1803 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1804 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1809 my ( $record, $marcflavour ) = @_;
1811 carp 'GetMarcUrls called on undefined record';
1816 for my $field ( $record->field('856') ) {
1818 for my $note ( $field->subfield('z') ) {
1819 push @notes, { note => $note };
1821 my @urls = $field->subfield('u');
1822 foreach my $url (@urls) {
1823 $url =~ s/^\s+|\s+$//g; # trim
1825 if ( $marcflavour eq 'MARC21' ) {
1826 my $s3 = $field->subfield('3');
1827 my $link = $field->subfield('y');
1828 unless ( $url =~ /^\w+:/ ) {
1829 if ( $field->indicator(1) eq '7' ) {
1830 $url = $field->subfield('2') . "://" . $url;
1831 } elsif ( $field->indicator(1) eq '1' ) {
1832 $url = 'ftp://' . $url;
1835 # properly, this should be if ind1=4,
1836 # however we will assume http protocol since we're building a link.
1837 $url = 'http://' . $url;
1841 # TODO handle ind 2 (relationship)
1846 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1847 $marcurl->{'part'} = $s3 if ($link);
1848 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1850 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1851 $marcurl->{'MARCURL'} = $url;
1853 push @marcurls, $marcurl;
1859 =head2 GetMarcSeries
1861 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1863 Get all series from the MARC record and returns them in an array.
1864 The series are stored in different fields depending on MARC flavour
1869 my ( $record, $marcflavour ) = @_;
1871 carp 'GetMarcSeries called on undefined record';
1875 my ( $mintag, $maxtag, $fields_filter );
1876 if ( $marcflavour eq "UNIMARC" ) {
1879 $fields_filter = '2..';
1880 } else { # marc21/normarc
1883 $fields_filter = '4..';
1887 my $AuthoritySeparator = C4::Context->preference('AuthoritySeparator');
1889 foreach my $field ( $record->field($fields_filter) ) {
1890 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1892 my @subfields = $field->subfields();
1895 for my $series_subfield (@subfields) {
1897 # ignore $9, used for authority link
1898 next if ( $series_subfield->[0] eq '9' );
1901 my $code = $series_subfield->[0];
1902 my $value = $series_subfield->[1];
1903 my $linkvalue = $value;
1904 $linkvalue =~ s/(\(|\))//g;
1906 # see if this is an instance of a volume
1907 if ( $code eq 'v' ) {
1912 'link' => $linkvalue,
1913 operator => (scalar @link_loop) ? ' and ' : undef
1916 if ($volume_number) {
1917 push @subfields_loop, { volumenum => $value };
1919 push @subfields_loop, {
1922 link_loop => \@link_loop,
1923 separator => (scalar @subfields_loop) ? $AuthoritySeparator : '',
1924 volumenum => $volume_number,
1928 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1931 return \@marcseries;
1932 } #end getMARCseriess
1936 $marchostsarray = GetMarcHosts($record,$marcflavour);
1938 Get all host records (773s MARC21, 461 UNIMARC) from the MARC record and returns them in an array.
1943 my ( $record, $marcflavour ) = @_;
1945 carp 'GetMarcHosts called on undefined record';
1949 my ( $tag,$title_subf,$bibnumber_subf,$itemnumber_subf);
1950 $marcflavour ||="MARC21";
1951 if ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) {
1954 $bibnumber_subf ="0";
1955 $itemnumber_subf='9';
1957 elsif ($marcflavour eq "UNIMARC") {
1960 $bibnumber_subf ="0";
1961 $itemnumber_subf='9';
1966 foreach my $field ( $record->field($tag)) {
1970 my $hostbiblionumber = $field->subfield("$bibnumber_subf");
1971 my $hosttitle = $field->subfield($title_subf);
1972 my $hostitemnumber=$field->subfield($itemnumber_subf);
1973 push @fields_loop, { hostbiblionumber => $hostbiblionumber, hosttitle => $hosttitle, hostitemnumber => $hostitemnumber};
1974 push @marchosts, { MARCHOSTS_FIELDS_LOOP => \@fields_loop };
1977 my $marchostsarray = \@marchosts;
1978 return $marchostsarray;
1981 =head2 UpsertMarcSubfield
1983 my $record = C4::Biblio::UpsertMarcSubfield($MARC::Record, $fieldTag, $subfieldCode, $subfieldContent);
1987 sub UpsertMarcSubfield {
1988 my ($record, $tag, $code, $content) = @_;
1989 my $f = $record->field($tag);
1992 $f->update( $code => $content );
1995 my $f = MARC::Field->new( $tag, '', '', $code => $content);
1996 $record->insert_fields_ordered( $f );
2000 =head2 UpsertMarcControlField
2002 my $record = C4::Biblio::UpsertMarcControlField($MARC::Record, $fieldTag, $content);
2006 sub UpsertMarcControlField {
2007 my ($record, $tag, $content) = @_;
2008 die "UpsertMarcControlField() \$tag '$tag' is not a control field\n" unless 0+$tag < 10;
2009 my $f = $record->field($tag);
2012 $f->update( $content );
2015 my $f = MARC::Field->new($tag, $content);
2016 $record->insert_fields_ordered( $f );
2020 =head2 GetFrameworkCode
2022 $frameworkcode = GetFrameworkCode( $biblionumber )
2026 sub GetFrameworkCode {
2027 my ($biblionumber) = @_;
2028 my $dbh = C4::Context->dbh;
2029 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
2030 $sth->execute($biblionumber);
2031 my ($frameworkcode) = $sth->fetchrow;
2032 return $frameworkcode;
2035 =head2 TransformKohaToMarc
2037 $record = TransformKohaToMarc( $hash [, $params ] )
2039 This function builds a (partial) MARC::Record from a hash.
2040 Hash entries can be from biblio, biblioitems or items.
2041 The params hash includes the parameter no_split used in C4::Items.
2043 This function is called in acquisition module, to create a basic catalogue
2044 entry from user entry.
2049 sub TransformKohaToMarc {
2050 my ( $hash, $params ) = @_;
2051 my $record = MARC::Record->new();
2052 SetMarcUnicodeFlag( $record, C4::Context->preference("marcflavour") );
2054 # In the next call we use the Default framework, since it is considered
2055 # authoritative for Koha to Marc mappings.
2056 my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # do not change framewok
2058 while ( my ($kohafield, $value) = each %$hash ) {
2059 foreach my $fld ( @{ $mss->{$kohafield} } ) {
2060 my $tagfield = $fld->{tagfield};
2061 my $tagsubfield = $fld->{tagsubfield};
2063 my @values = $params->{no_split}
2065 : split(/\s?\|\s?/, $value, -1);
2066 foreach my $value ( @values ) {
2067 next if $value eq '';
2068 $tag_hr->{$tagfield} //= [];
2069 push @{$tag_hr->{$tagfield}}, [($tagsubfield, $value)];
2073 foreach my $tag (sort keys %$tag_hr) {
2074 my @sfl = @{$tag_hr->{$tag}};
2075 @sfl = sort { $a->[0] cmp $b->[0]; } @sfl;
2076 @sfl = map { @{$_}; } @sfl;
2077 # Special care for control fields: remove the subfield indication @
2078 # and do not insert indicators.
2079 my @ind = $tag < 10 ? () : ( " ", " " );
2080 @sfl = grep { $_ ne '@' } @sfl if $tag < 10;
2081 $record->insert_fields_ordered( MARC::Field->new($tag, @ind, @sfl) );
2086 =head2 PrepHostMarcField
2088 $hostfield = PrepHostMarcField ( $hostbiblionumber,$hostitemnumber,$marcflavour )
2090 This function returns a host field populated with data from the host record, the field can then be added to an analytical record
2094 sub PrepHostMarcField {
2095 my ($hostbiblionumber,$hostitemnumber, $marcflavour) = @_;
2096 $marcflavour ||="MARC21";
2098 my $hostrecord = GetMarcBiblio({ biblionumber => $hostbiblionumber });
2099 my $item = Koha::Items->find($hostitemnumber);
2102 if ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) {
2106 if ($hostrecord->subfield('100','a')){
2107 $mainentry = $hostrecord->subfield('100','a');
2108 } elsif ($hostrecord->subfield('110','a')){
2109 $mainentry = $hostrecord->subfield('110','a');
2111 $mainentry = $hostrecord->subfield('111','a');
2114 # qualification info
2116 if (my $field260 = $hostrecord->field('260')){
2117 $qualinfo = $field260->as_string( 'abc' );
2122 my $ed = $hostrecord->subfield('250','a');
2123 my $barcode = $item->barcode;
2124 my $title = $hostrecord->subfield('245','a');
2126 # record control number, 001 with 003 and prefix
2128 if ($hostrecord->field('001')){
2129 $recctrlno = $hostrecord->field('001')->data();
2130 if ($hostrecord->field('003')){
2131 $recctrlno = '('.$hostrecord->field('003')->data().')'.$recctrlno;
2136 my $issn = $hostrecord->subfield('022','a');
2137 my $isbn = $hostrecord->subfield('020','a');
2140 $hostmarcfield = MARC::Field->new(
2142 '0' => $hostbiblionumber,
2143 '9' => $hostitemnumber,
2153 } elsif ($marcflavour eq "UNIMARC") {
2154 $hostmarcfield = MARC::Field->new(
2156 '0' => $hostbiblionumber,
2157 't' => $hostrecord->subfield('200','a'),
2158 '9' => $hostitemnumber
2162 return $hostmarcfield;
2165 =head2 TransformHtmlToXml
2167 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator,
2168 $ind_tag, $auth_type )
2170 $auth_type contains :
2174 =item - nothing : rebuild a biblio. In UNIMARC the encoding is in 100$a pos 26/27
2176 =item - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
2178 =item - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
2184 sub TransformHtmlToXml {
2185 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
2186 # NOTE: The parameter $ind_tag is NOT USED -- BZ 11247
2188 my $xml = MARC::File::XML::header('UTF-8');
2189 $xml .= "<record>\n";
2190 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
2191 MARC::File::XML->default_record_format($auth_type);
2193 # in UNIMARC, field 100 contains the encoding
2194 # check that there is one, otherwise the
2195 # MARC::Record->new_from_xml will fail (and Koha will die)
2196 my $unimarc_and_100_exist = 0;
2197 $unimarc_and_100_exist = 1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2203 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
2205 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a" ) {
2207 # if we have a 100 field and it's values are not correct, skip them.
2208 # if we don't have any valid 100 field, we will create a default one at the end
2209 my $enc = substr( @$values[$i], 26, 2 );
2210 if ( $enc eq '01' or $enc eq '50' or $enc eq '03' ) {
2211 $unimarc_and_100_exist = 1;
2216 @$values[$i] =~ s/&/&/g;
2217 @$values[$i] =~ s/</</g;
2218 @$values[$i] =~ s/>/>/g;
2219 @$values[$i] =~ s/"/"/g;
2220 @$values[$i] =~ s/'/'/g;
2222 if ( ( @$tags[$i] ne $prevtag ) ) {
2223 $close_last_tag = 0;
2224 $j++ unless ( @$tags[$i] eq "" );
2225 my $str = ( $indicator->[$j] // q{} ) . ' '; # extra space prevents substr outside of string warn
2226 my $ind1 = _default_ind_to_space( substr( $str, 0, 1 ) );
2227 my $ind2 = _default_ind_to_space( substr( $str, 1, 1 ) );
2229 $xml .= "</datafield>\n";
2230 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2231 && ( @$values[$i] ne "" ) ) {
2232 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2233 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2235 $close_last_tag = 1;
2240 if ( @$values[$i] ne "" ) {
2243 if ( @$tags[$i] eq "000" ) {
2244 $xml .= "<leader>@$values[$i]</leader>\n";
2247 # rest of the fixed fields
2248 } elsif ( @$tags[$i] < 10 ) {
2249 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2252 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2253 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2255 $close_last_tag = 1;
2259 } else { # @$tags[$i] eq $prevtag
2260 if ( @$values[$i] eq "" ) {
2263 my $str = ( $indicator->[$j] // q{} ) . ' '; # extra space prevents substr outside of string warn
2264 my $ind1 = _default_ind_to_space( substr( $str, 0, 1 ) );
2265 my $ind2 = _default_ind_to_space( substr( $str, 1, 1 ) );
2266 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2268 $close_last_tag = 1;
2270 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2273 $prevtag = @$tags[$i];
2275 $xml .= "</datafield>\n" if $close_last_tag;
2276 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist ) {
2278 # warn "SETTING 100 for $auth_type";
2279 my $string = strftime( "%Y%m%d", localtime(time) );
2281 # set 50 to position 26 is biblios, 13 if authorities
2283 $pos = 13 if $auth_type eq 'UNIMARCAUTH';
2284 $string = sprintf( "%-*s", 35, $string );
2285 substr( $string, $pos, 6, "50" );
2286 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2287 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2288 $xml .= "</datafield>\n";
2290 $xml .= "</record>\n";
2291 $xml .= MARC::File::XML::footer();
2295 =head2 _default_ind_to_space
2297 Passed what should be an indicator returns a space
2298 if its undefined or zero length
2302 sub _default_ind_to_space {
2304 if ( !defined $s || $s eq q{} ) {
2310 =head2 TransformHtmlToMarc
2312 L<$record> = TransformHtmlToMarc(L<$cgi>)
2313 L<$cgi> is the CGI object which contains the values for subfields
2315 'tag_010_indicator1_531951' ,
2316 'tag_010_indicator2_531951' ,
2317 'tag_010_code_a_531951_145735' ,
2318 'tag_010_subfield_a_531951_145735' ,
2319 'tag_200_indicator1_873510' ,
2320 'tag_200_indicator2_873510' ,
2321 'tag_200_code_a_873510_673465' ,
2322 'tag_200_subfield_a_873510_673465' ,
2323 'tag_200_code_b_873510_704318' ,
2324 'tag_200_subfield_b_873510_704318' ,
2325 'tag_200_code_e_873510_280822' ,
2326 'tag_200_subfield_e_873510_280822' ,
2327 'tag_200_code_f_873510_110730' ,
2328 'tag_200_subfield_f_873510_110730' ,
2330 L<$record> is the MARC::Record object.
2334 sub TransformHtmlToMarc {
2335 my ($cgi, $isbiblio) = @_;
2337 my @params = $cgi->multi_param();
2339 # explicitly turn on the UTF-8 flag for all
2340 # 'tag_' parameters to avoid incorrect character
2341 # conversion later on
2342 my $cgi_params = $cgi->Vars;
2343 foreach my $param_name ( keys %$cgi_params ) {
2344 if ( $param_name =~ /^tag_/ ) {
2345 my $param_value = $cgi_params->{$param_name};
2346 unless ( Encode::is_utf8( $param_value ) ) {
2347 $cgi_params->{$param_name} = Encode::decode('UTF-8', $param_value );
2352 # creating a new record
2353 my $record = MARC::Record->new();
2355 my ($biblionumbertagfield, $biblionumbertagsubfield) = (-1, -1);
2356 ($biblionumbertagfield, $biblionumbertagsubfield) =
2357 &GetMarcFromKohaField( "biblio.biblionumber", '' ) if $isbiblio;
2358 #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!
2359 for (my $i = 0; $params[$i]; $i++ ) { # browse all CGI params
2360 my $param = $params[$i];
2363 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2364 if ( $param eq 'biblionumber' ) {
2365 if ( $biblionumbertagfield < 10 ) {
2366 $newfield = MARC::Field->new( $biblionumbertagfield, scalar $cgi->param($param), );
2368 $newfield = MARC::Field->new( $biblionumbertagfield, '', '', "$biblionumbertagsubfield" => scalar $cgi->param($param), );
2370 push @fields, $newfield if ($newfield);
2371 } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..."
2374 my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) );
2375 my $ind2 = _default_ind_to_space( substr( $cgi->param( $params[ $i + 1 ] ), 0, 1 ) );
2379 if ( $tag < 10 ) { # no code for theses fields
2380 # in MARC editor, 000 contains the leader.
2381 next if $tag == $biblionumbertagfield;
2382 my $fval= $cgi->param($params[$j+1]);
2383 if ( $tag eq '000' ) {
2384 # Force a fake leader even if not provided to avoid crashing
2385 # during decoding MARC record containing UTF-8 characters
2387 length( $fval ) == 24
2392 # between 001 and 009 (included)
2393 } elsif ( $fval ne '' ) {
2394 $newfield = MARC::Field->new( $tag, $fval, );
2397 # > 009, deal with subfields
2399 # browse subfields for this tag (reason for _code_ match)
2400 while(defined $params[$j] && $params[$j] =~ /_code_/) {
2401 last unless defined $params[$j+1];
2403 if $tag == $biblionumbertagfield and
2404 $cgi->param($params[$j]) eq $biblionumbertagsubfield;
2405 #if next param ne subfield, then it was probably empty
2406 #try next param by incrementing j
2407 if($params[$j+1]!~/_subfield_/) {$j++; next; }
2408 my $fkey= $cgi->param($params[$j]);
2409 my $fval= $cgi->param($params[$j+1]);
2410 #check if subfield value not empty and field exists
2411 if($fval ne '' && $newfield) {
2412 $newfield->add_subfields( $fkey => $fval);
2414 elsif($fval ne '') {
2415 $newfield = MARC::Field->new( $tag, $ind1, $ind2, $fkey => $fval );
2419 $i= $j-1; #update i for outer loop accordingly
2421 push @fields, $newfield if ($newfield);
2425 @fields = sort { $a->tag() cmp $b->tag() } @fields;
2426 $record->append_fields(@fields);
2430 =head2 TransformMarcToKoha
2432 $result = TransformMarcToKoha( $record, undef, $limit )
2434 Extract data from a MARC bib record into a hashref representing
2435 Koha biblio, biblioitems, and items fields.
2437 If passed an undefined record will log the error and return an empty
2442 sub TransformMarcToKoha {
2443 my ( $record, $frameworkcode, $limit_table ) = @_;
2444 # FIXME Parameter $frameworkcode is obsolete and will be removed
2445 $limit_table //= q{};
2448 if (!defined $record) {
2449 carp('TransformMarcToKoha called with undefined record');
2453 my %tables = ( biblio => 1, biblioitems => 1, items => 1 );
2454 if( $limit_table eq 'items' ) {
2455 %tables = ( items => 1 );
2458 # The next call acknowledges Default as the authoritative framework
2459 # for Koha to MARC mappings.
2460 my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework
2461 foreach my $kohafield ( keys %{ $mss } ) {
2462 my ( $table, $column ) = split /[.]/, $kohafield, 2;
2463 next unless $tables{$table};
2464 my $val = TransformMarcToKohaOneField( $kohafield, $record );
2465 next if !defined $val;
2466 my $key = _disambiguate( $table, $column );
2467 $result->{$key} = $val;
2472 =head2 _disambiguate
2474 $newkey = _disambiguate($table, $field);
2476 This is a temporary hack to distinguish between the
2477 following sets of columns when using TransformMarcToKoha.
2479 items.cn_source & biblioitems.cn_source
2480 items.cn_sort & biblioitems.cn_sort
2482 Columns that are currently NOT distinguished (FIXME
2483 due to lack of time to fully test) are:
2485 biblio.notes and biblioitems.notes
2490 FIXME - this is necessary because prefixing each column
2491 name with the table name would require changing lots
2492 of code and templates, and exposing more of the DB
2493 structure than is good to the UI templates, particularly
2494 since biblio and bibloitems may well merge in a future
2495 version. In the future, it would also be good to
2496 separate DB access and UI presentation field names
2502 my ( $table, $column ) = @_;
2503 if ( $column eq "cn_sort" or $column eq "cn_source" ) {
2504 return $table . '.' . $column;
2511 =head2 TransformMarcToKohaOneField
2513 $val = TransformMarcToKohaOneField( 'biblio.title', $marc );
2515 Note: The authoritative Default framework is used implicitly.
2519 sub TransformMarcToKohaOneField {
2520 my ( $kohafield, $marc ) = @_;
2522 my ( @rv, $retval );
2523 my @mss = GetMarcSubfieldStructureFromKohaField($kohafield);
2524 foreach my $fldhash ( @mss ) {
2525 my $tag = $fldhash->{tagfield};
2526 my $sub = $fldhash->{tagsubfield};
2527 foreach my $fld ( $marc->field($tag) ) {
2528 if( $sub eq '@' || $fld->is_control_field ) {
2529 push @rv, $fld->data if $fld->data;
2531 push @rv, grep { $_ } $fld->subfield($sub);
2536 $retval = join ' | ', uniq(@rv);
2538 # Additional polishing for individual kohafields
2539 if( $kohafield =~ /copyrightdate|publicationyear/ ) {
2540 $retval = _adjust_pubyear( $retval );
2546 =head2 _adjust_pubyear
2548 Helper routine for TransformMarcToKohaOneField
2552 sub _adjust_pubyear {
2554 # modify return value to keep only the 1st year found
2555 if( $retval =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2557 } elsif( $retval =~ m/(\d\d\d\d)/ && $1 > 0 ) {
2559 } elsif( $retval =~ m/
2560 (?<year>\d)[-]?[.Xx?]{3}
2561 |(?<year>\d{2})[.Xx?]{2}
2562 |(?<year>\d{3})[.Xx?]
2563 |(?<year>\d)[-]{3}\?
2564 |(?<year>\d\d)[-]{2}\?
2565 |(?<year>\d{3})[-]\?
2566 /xms ) { # the form 198-? occurred in Dutch ISBD rules
2567 my $digits = $+{year};
2568 $retval = $digits * ( 10 ** ( 4 - length($digits) ));
2575 =head2 CountItemsIssued
2577 my $count = CountItemsIssued( $biblionumber );
2581 sub CountItemsIssued {
2582 my ($biblionumber) = @_;
2583 my $dbh = C4::Context->dbh;
2584 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2585 $sth->execute($biblionumber);
2586 my $row = $sth->fetchrow_hashref();
2587 return $row->{'issuedCount'};
2592 ModZebra( $biblionumber, $op, $server, $record );
2594 $biblionumber is the biblionumber we want to index
2596 $op is specialUpdate or recordDelete, and is used to know what we want to do
2598 $server is the server that we want to update
2600 $record is the updated MARC record. If it's not supplied
2601 and is needed it will be loaded from the database.
2606 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2607 my ( $biblionumber, $op, $server, $record ) = @_;
2608 $debug && warn "ModZebra: update requested for: $biblionumber $op $server\n";
2609 if ( C4::Context->preference('SearchEngine') eq 'Elasticsearch' ) {
2611 # TODO abstract to a standard API that'll work for whatever
2612 require Koha::SearchEngine::Elasticsearch::Indexer;
2613 my $indexer = Koha::SearchEngine::Elasticsearch::Indexer->new(
2615 index => $server eq 'biblioserver'
2616 ? $Koha::SearchEngine::BIBLIOS_INDEX
2617 : $Koha::SearchEngine::AUTHORITIES_INDEX
2620 if ( $op eq 'specialUpdate' ) {
2622 $record = GetMarcBiblio({
2623 biblionumber => $biblionumber,
2624 embed_items => 1 });
2626 $indexer->update_index_background( [$biblionumber], [$record] );
2628 elsif ( $op eq 'recordDelete' ) {
2629 $indexer->delete_index_background( [$biblionumber] );
2632 croak "ModZebra called with unknown operation: $op";
2636 my $dbh = C4::Context->dbh;
2638 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2640 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2641 # the table is emptied by rebuild_zebra.pl script (using the -z switch)
2642 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2644 AND biblio_auth_number = ?
2647 my $check_sth = $dbh->prepare_cached($check_sql);
2648 $check_sth->execute( $server, $biblionumber, $op );
2649 my ($count) = $check_sth->fetchrow_array;
2650 $check_sth->finish();
2651 if ( $count == 0 ) {
2652 my $sth = $dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2653 $sth->execute( $biblionumber, $server, $op );
2659 =head2 EmbedItemsInMarcBiblio
2661 EmbedItemsInMarcBiblio({
2662 marc_record => $marc,
2663 biblionumber => $biblionumber,
2664 item_numbers => $itemnumbers,
2667 Given a MARC::Record object containing a bib record,
2668 modify it to include the items attached to it as 9XX
2669 per the bib's MARC framework.
2670 if $itemnumbers is defined, only specified itemnumbers are embedded.
2672 If $opac is true, then opac-relevant suppressions are included.
2674 If opac filtering will be done, borcat should be passed to properly
2675 override if necessary.
2679 sub EmbedItemsInMarcBiblio {
2681 my ($marc, $biblionumber, $itemnumbers, $opac, $borcat);
2682 $marc = $params->{marc_record};
2684 carp 'EmbedItemsInMarcBiblio: No MARC record passed';
2687 $biblionumber = $params->{biblionumber};
2688 $itemnumbers = $params->{item_numbers};
2689 $opac = $params->{opac};
2690 $borcat = $params->{borcat} // q{};
2692 $itemnumbers = [] unless defined $itemnumbers;
2694 my $frameworkcode = GetFrameworkCode($biblionumber);
2695 _strip_item_fields($marc, $frameworkcode);
2697 # ... and embed the current items
2698 my $dbh = C4::Context->dbh;
2699 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
2700 $sth->execute($biblionumber);
2701 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" );
2703 my @item_fields; # Array holding the actual MARC data for items to be included.
2704 my @items; # Array holding items which are both in the list (sitenumbers)
2705 # and on this biblionumber
2707 # Flag indicating if there is potential hiding.
2708 my $opachiddenitems = $opac
2709 && ( C4::Context->preference('OpacHiddenItems') !~ /^\s*$/ );
2712 while ( my ($itemnumber) = $sth->fetchrow_array ) {
2713 next if @$itemnumbers and not grep { $_ == $itemnumber } @$itemnumbers;
2715 if ( $opachiddenitems ) {
2716 $item = Koha::Items->find($itemnumber);
2717 $item = $item ? $item->unblessed : undef;
2719 push @items, { itemnumber => $itemnumber, item => $item };
2721 my @items2pass = map { $_->{item} } @items;
2724 ? C4::Items::GetHiddenItemnumbers({
2725 items => \@items2pass,
2726 borcat => $borcat })
2728 # Convert to a hash for quick searching
2729 my %hiddenitems = map { $_ => 1 } @hiddenitems;
2730 foreach my $itemnumber ( map { $_->{itemnumber} } @items ) {
2731 next if $hiddenitems{$itemnumber};
2732 my $item_marc = C4::Items::GetMarcItem( $biblionumber, $itemnumber );
2733 push @item_fields, $item_marc->field($itemtag);
2735 $marc->append_fields(@item_fields);
2738 =head1 INTERNAL FUNCTIONS
2740 =head2 _koha_marc_update_bib_ids
2743 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2745 Internal function to add or update biblionumber and biblioitemnumber to
2750 sub _koha_marc_update_bib_ids {
2751 my ( $record, $frameworkcode, $biblionumber, $biblioitemnumber ) = @_;
2753 my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField( "biblio.biblionumber" );
2754 die qq{No biblionumber tag for framework "$frameworkcode"} unless $biblio_tag;
2755 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber" );
2756 die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag;
2758 if ( $biblio_tag < 10 ) {
2759 C4::Biblio::UpsertMarcControlField( $record, $biblio_tag, $biblionumber );
2761 C4::Biblio::UpsertMarcSubfield($record, $biblio_tag, $biblio_subfield, $biblionumber);
2763 if ( $biblioitem_tag < 10 ) {
2764 C4::Biblio::UpsertMarcControlField( $record, $biblioitem_tag, $biblioitemnumber );
2766 C4::Biblio::UpsertMarcSubfield($record, $biblioitem_tag, $biblioitem_subfield, $biblioitemnumber);
2770 =head2 _koha_marc_update_biblioitem_cn_sort
2772 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2774 Given a MARC bib record and the biblioitem hash, update the
2775 subfield that contains a copy of the value of biblioitems.cn_sort.
2779 sub _koha_marc_update_biblioitem_cn_sort {
2781 my $biblioitem = shift;
2782 my $frameworkcode = shift;
2784 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.cn_sort" );
2785 return unless $biblioitem_tag;
2787 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2789 if ( my $field = $marc->field($biblioitem_tag) ) {
2790 $field->delete_subfield( code => $biblioitem_subfield );
2791 if ( $cn_sort ne '' ) {
2792 $field->add_subfields( $biblioitem_subfield => $cn_sort );
2796 # if we get here, no biblioitem tag is present in the MARC record, so
2797 # we'll create it if $cn_sort is not empty -- this would be
2798 # an odd combination of events, however
2800 $marc->insert_grouped_field( MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) );
2805 =head2 _koha_modify_biblio
2807 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2809 Internal function for updating the biblio table
2813 sub _koha_modify_biblio {
2814 my ( $dbh, $biblio, $frameworkcode ) = @_;
2819 SET frameworkcode = ?,
2832 WHERE biblionumber = ?
2835 my $sth = $dbh->prepare($query);
2838 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'subtitle'},
2839 $biblio->{'medium'}, $biblio->{'part_number'}, $biblio->{'part_name'}, $biblio->{'unititle'},
2840 $biblio->{'notes'}, $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'} ? int($biblio->{'copyrightdate'}) : undef,
2841 $biblio->{'abstract'}, $biblio->{'biblionumber'}
2842 ) if $biblio->{'biblionumber'};
2844 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
2845 $error .= "ERROR in _koha_modify_biblio $query" . $dbh->errstr;
2848 return ( $biblio->{'biblionumber'}, $error );
2851 =head2 _koha_modify_biblioitem_nonmarc
2853 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
2857 sub _koha_modify_biblioitem_nonmarc {
2858 my ( $dbh, $biblioitem ) = @_;
2861 # re-calculate the cn_sort, it may have changed
2862 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2864 my $query = "UPDATE biblioitems
2865 SET biblionumber = ?,
2871 publicationyear = ?,
2875 collectiontitle = ?,
2877 collectionvolume= ?,
2878 editionstatement= ?,
2879 editionresponsibility = ?,
2895 where biblioitemnumber = ?
2897 my $sth = $dbh->prepare($query);
2899 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
2900 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
2901 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
2902 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
2903 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
2904 $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'},
2905 $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'},
2906 $biblioitem->{'ean'}, $biblioitem->{'agerestriction'}, $biblioitem->{'biblioitemnumber'}
2908 if ( $dbh->errstr ) {
2909 $error .= "ERROR in _koha_modify_biblioitem_nonmarc $query" . $dbh->errstr;
2912 return ( $biblioitem->{'biblioitemnumber'}, $error );
2915 =head2 _koha_delete_biblio
2917 $error = _koha_delete_biblio($dbh,$biblionumber);
2919 Internal sub for deleting from biblio table -- also saves to deletedbiblio
2921 C<$dbh> - the database handle
2923 C<$biblionumber> - the biblionumber of the biblio to be deleted
2927 # FIXME: add error handling
2929 sub _koha_delete_biblio {
2930 my ( $dbh, $biblionumber ) = @_;
2932 # get all the data for this biblio
2933 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
2934 $sth->execute($biblionumber);
2936 # FIXME There is a transaction in _koha_delete_biblio_metadata
2937 # But actually all the following should be done inside a single transaction
2938 if ( my $data = $sth->fetchrow_hashref ) {
2940 # save the record in deletedbiblio
2941 # find the fields to save
2942 my $query = "INSERT INTO deletedbiblio SET ";
2944 foreach my $temp ( keys %$data ) {
2945 $query .= "$temp = ?,";
2946 push( @bind, $data->{$temp} );
2949 # replace the last , by ",?)"
2951 my $bkup_sth = $dbh->prepare($query);
2952 $bkup_sth->execute(@bind);
2955 _koha_delete_biblio_metadata( $biblionumber );
2958 my $sth2 = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
2959 $sth2->execute($biblionumber);
2960 # update the timestamp (Bugzilla 7146)
2961 $sth2= $dbh->prepare("UPDATE deletedbiblio SET timestamp=NOW() WHERE biblionumber=?");
2962 $sth2->execute($biblionumber);
2969 =head2 _koha_delete_biblioitems
2971 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
2973 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
2975 C<$dbh> - the database handle
2976 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
2980 # FIXME: add error handling
2982 sub _koha_delete_biblioitems {
2983 my ( $dbh, $biblioitemnumber ) = @_;
2985 # get all the data for this biblioitem
2986 my $sth = $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
2987 $sth->execute($biblioitemnumber);
2989 if ( my $data = $sth->fetchrow_hashref ) {
2991 # save the record in deletedbiblioitems
2992 # find the fields to save
2993 my $query = "INSERT INTO deletedbiblioitems SET ";
2995 foreach my $temp ( keys %$data ) {
2996 $query .= "$temp = ?,";
2997 push( @bind, $data->{$temp} );
3000 # replace the last , by ",?)"
3002 my $bkup_sth = $dbh->prepare($query);
3003 $bkup_sth->execute(@bind);
3006 # delete the biblioitem
3007 my $sth2 = $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3008 $sth2->execute($biblioitemnumber);
3009 # update the timestamp (Bugzilla 7146)
3010 $sth2= $dbh->prepare("UPDATE deletedbiblioitems SET timestamp=NOW() WHERE biblioitemnumber=?");
3011 $sth2->execute($biblioitemnumber);
3018 =head2 _koha_delete_biblio_metadata
3020 $error = _koha_delete_biblio_metadata($biblionumber);
3022 C<$biblionumber> - the biblionumber of the biblio metadata to be deleted
3026 sub _koha_delete_biblio_metadata {
3027 my ($biblionumber) = @_;
3029 my $dbh = C4::Context->dbh;
3030 my $schema = Koha::Database->new->schema;
3034 INSERT INTO deletedbiblio_metadata (biblionumber, format, `schema`, metadata)
3035 SELECT biblionumber, format, `schema`, metadata FROM biblio_metadata WHERE biblionumber=?
3036 |, undef, $biblionumber );
3037 $dbh->do( q|DELETE FROM biblio_metadata WHERE biblionumber=?|,
3038 undef, $biblionumber );
3043 =head1 UNEXPORTED FUNCTIONS
3045 =head2 ModBiblioMarc
3047 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3049 Add MARC XML data for a biblio to koha
3051 Function exported, but should NOT be used, unless you really know what you're doing
3056 # pass the MARC::Record to this function, and it will create the records in
3058 my ( $record, $biblionumber, $frameworkcode ) = @_;
3060 carp 'ModBiblioMarc passed an undefined record';
3064 # Clone record as it gets modified
3065 $record = $record->clone();
3066 my $dbh = C4::Context->dbh;
3067 my @fields = $record->fields();
3068 if ( !$frameworkcode ) {
3069 $frameworkcode = "";
3071 my $sth = $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3072 $sth->execute( $frameworkcode, $biblionumber );
3074 my $encoding = C4::Context->preference("marcflavour");
3076 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3077 if ( $encoding eq "UNIMARC" ) {
3078 my $defaultlanguage = C4::Context->preference("UNIMARCField100Language");
3079 $defaultlanguage = "fre" if (!$defaultlanguage || length($defaultlanguage) != 3);
3080 my $string = $record->subfield( 100, "a" );
3081 if ( ($string) && ( length( $record->subfield( 100, "a" ) ) == 36 ) ) {
3082 my $f100 = $record->field(100);
3083 $record->delete_field($f100);
3085 $string = POSIX::strftime( "%Y%m%d", localtime );
3087 $string = sprintf( "%-*s", 35, $string );
3088 substr ( $string, 22, 3, $defaultlanguage);
3090 substr( $string, 25, 3, "y50" );
3091 unless ( $record->subfield( 100, "a" ) ) {
3092 $record->insert_fields_ordered( MARC::Field->new( 100, "", "", "a" => $string ) );
3096 #enhancement 5374: update transaction date (005) for marc21/unimarc
3097 if($encoding =~ /MARC21|UNIMARC/) {
3098 my @a= (localtime) [5,4,3,2,1,0]; $a[0]+=1900; $a[1]++;
3099 # YY MM DD HH MM SS (update year and month)
3100 my $f005= $record->field('005');
3101 $f005->update(sprintf("%4d%02d%02d%02d%02d%04.1f",@a)) if $f005;
3105 biblionumber => $biblionumber,
3106 format => 'marcxml',
3107 schema => C4::Context->preference('marcflavour'),
3109 $record->as_usmarc; # Bug 20126/10455 This triggers field length calculation
3111 my $m_rs = Koha::Biblio::Metadatas->find($metadata) //
3112 Koha::Biblio::Metadata->new($metadata);
3114 my $userenv = C4::Context->userenv;
3116 my $borrowernumber = $userenv->{number};
3117 my $borrowername = join ' ', map { $_ // q{} } @$userenv{qw(firstname surname)};
3118 unless ($m_rs->in_storage) {
3119 Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForCreatorId'), $borrowernumber);
3120 Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForCreatorName'), $borrowername);
3122 Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForModifierId'), $borrowernumber);
3123 Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForModifierName'), $borrowername);
3126 $m_rs->metadata( $record->as_xml_record($encoding) );
3129 ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
3131 return $biblionumber;
3134 =head2 CountBiblioInOrders
3136 $count = &CountBiblioInOrders( $biblionumber);
3138 This function return count of biblios in orders with $biblionumber
3142 sub CountBiblioInOrders {
3143 my ($biblionumber) = @_;
3144 my $dbh = C4::Context->dbh;
3145 my $query = "SELECT count(*)
3147 WHERE biblionumber=? AND datecancellationprinted IS NULL";
3148 my $sth = $dbh->prepare($query);
3149 $sth->execute($biblionumber);
3150 my $count = $sth->fetchrow;
3154 =head2 prepare_host_field
3156 $marcfield = prepare_host_field( $hostbiblioitem, $marcflavour );
3157 Generate the host item entry for an analytic child entry
3161 sub prepare_host_field {
3162 my ( $hostbiblio, $marcflavour ) = @_;
3163 $marcflavour ||= C4::Context->preference('marcflavour');
3164 my $host = GetMarcBiblio({ biblionumber => $hostbiblio });
3165 # unfortunately as_string does not 'do the right thing'
3166 # if field returns undef
3170 if ( $marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC' ) {
3171 if ( $field = $host->field('100') || $host->field('110') || $host->field('11') ) {
3172 my $s = $field->as_string('ab');
3177 if ( $field = $host->field('245') ) {
3178 my $s = $field->as_string('a');
3183 if ( $field = $host->field('260') ) {
3184 my $s = $field->as_string('abc');
3189 if ( $field = $host->field('240') ) {
3190 my $s = $field->as_string();
3195 if ( $field = $host->field('022') ) {
3196 my $s = $field->as_string('a');
3201 if ( $field = $host->field('020') ) {
3202 my $s = $field->as_string('a');
3207 if ( $field = $host->field('001') ) {
3208 $sfd{w} = $field->data(),;
3210 $host_field = MARC::Field->new( 773, '0', ' ', %sfd );
3213 elsif ( $marcflavour eq 'UNIMARC' ) {
3215 if ( $field = $host->field('700') || $host->field('710') || $host->field('720') ) {
3216 my $s = $field->as_string('ab');
3222 if ( $field = $host->field('200') ) {
3223 my $s = $field->as_string('a');
3228 #place of publicaton
3229 if ( $field = $host->field('210') ) {
3230 my $s = $field->as_string('a');
3235 #date of publication
3236 if ( $field = $host->field('210') ) {
3237 my $s = $field->as_string('d');
3243 if ( $field = $host->field('205') ) {
3244 my $s = $field->as_string();
3250 if ( $field = $host->field('856') ) {
3251 my $s = $field->as_string('u');
3257 if ( $field = $host->field('011') ) {
3258 my $s = $field->as_string('a');
3264 if ( $field = $host->field('010') ) {
3265 my $s = $field->as_string('a');
3270 if ( $field = $host->field('001') ) {
3271 $sfd{0} = $field->data(),;
3273 $host_field = MARC::Field->new( 461, '0', ' ', %sfd );
3280 =head2 UpdateTotalIssues
3282 UpdateTotalIssues($biblionumber, $increase, [$value])
3284 Update the total issue count for a particular bib record.
3288 =item C<$biblionumber> is the biblionumber of the bib to update
3290 =item C<$increase> is the amount to increase (or decrease) the total issues count by
3292 =item C<$value> is the absolute value that total issues count should be set to. If provided, C<$increase> is ignored.
3298 sub UpdateTotalIssues {
3299 my ($biblionumber, $increase, $value) = @_;
3302 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
3304 carp "UpdateTotalIssues could not get biblio record";
3307 my $biblio = Koha::Biblios->find( $biblionumber );
3309 carp "UpdateTotalIssues could not get datas of biblio";
3312 my $biblioitem = $biblio->biblioitem;
3313 my ($totalissuestag, $totalissuessubfield) = GetMarcFromKohaField( 'biblioitems.totalissues' );
3314 unless ($totalissuestag) {
3315 return 1; # There is nothing to do
3318 if (defined $value) {
3319 $totalissues = $value;
3321 $totalissues = $biblioitem->totalissues + $increase;
3324 my $field = $record->field($totalissuestag);
3325 if (defined $field) {
3326 $field->update( $totalissuessubfield => $totalissues );
3328 $field = MARC::Field->new($totalissuestag, '0', '0',
3329 $totalissuessubfield => $totalissues);
3330 $record->insert_grouped_field($field);
3333 return ModBiblio($record, $biblionumber, $biblio->frameworkcode);
3338 &RemoveAllNsb($record);
3340 Removes all nsb/nse chars from a record
3347 carp 'RemoveAllNsb called with undefined record';
3351 SetUTF8Flag($record);
3353 foreach my $field ($record->fields()) {
3354 if ($field->is_control_field()) {
3355 $field->update(nsb_clean($field->data()));
3357 my @subfields = $field->subfields();
3359 foreach my $subfield (@subfields) {
3360 push @new_subfields, $subfield->[0] => nsb_clean($subfield->[1]);
3362 if (scalar(@new_subfields) > 0) {
3365 $new_field = MARC::Field->new(
3367 $field->indicator(1),
3368 $field->indicator(2),
3373 warn "error in RemoveAllNsb : $@";
3375 $field->replace_with($new_field);
3387 =head2 _after_biblio_action_hooks
3389 Helper method that takes care of calling all plugin hooks
3393 sub _after_biblio_action_hooks {
3396 my $biblio_id = $args->{biblio_id};
3397 my $action = $args->{action};
3399 if ( C4::Context->preference('UseKohaPlugins') && C4::Context->config("enable_plugins") ) {
3401 my @plugins = Koha::Plugins->new->GetPlugins({
3402 method => 'after_biblio_action',
3407 my $biblio = Koha::Biblios->find( $biblio_id );
3409 foreach my $plugin ( @plugins ) {
3411 $plugin->after_biblio_action({ action => $action, biblio => $biblio, biblio_id => $biblio_id });
3425 Koha Development Team <http://koha-community.org/>
3427 Paul POULAIN paul.poulain@free.fr
3429 Joshua Ferraro jmf@liblime.com