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>.
25 use Encode qw( decode is_utf8 );
27 use MARC::File::USMARC;
29 use POSIX qw(strftime);
30 use Module::Load::Conditional qw(can_load);
33 use C4::Log; # logaction
42 use Koha::Authority::Types;
43 use Koha::Acquisition::Currencies;
44 use Koha::Biblio::Metadata;
45 use Koha::Biblio::Metadatas;
48 use Koha::SearchEngine;
51 use vars qw(@ISA @EXPORT);
52 use vars qw($debug $cgi_debug);
57 @ISA = qw( Exporter );
72 GetBiblioItemByBiblioNumber
94 &GetAuthorisedValueDesc
96 &IsMarcStructureInternal
98 &GetMarcSubfieldStructureFromKohaField
108 # To modify something
116 # To delete something
121 # To link headings in a bib record
122 # to authority records.
125 &LinkBibHeadingsToAuthorities
129 # those functions are exported but should not be used
130 # they are useful in a few circumstances, so they are exported,
131 # but don't use them unless you are a core developer ;-)
147 C4::Biblio - cataloging management functions
151 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:
155 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
157 =item 2. as raw MARC in the Zebra index and storage engine
159 =item 3. as MARC XML in biblio_metadata.metadata
163 In the 3.0 version of Koha, the authoritative record-level information is in biblio_metadata.metadata
165 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.
169 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
171 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
175 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:
179 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
181 =item 2. _koha_* - low-level internal functions for managing the koha tables
183 =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.
185 =item 4. Zebra functions used to update the Zebra index
187 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
191 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 :
195 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
197 =item 2. add the biblionumber and biblioitemnumber into the MARC records
199 =item 3. save the marc record
203 =head1 EXPORTED FUNCTIONS
207 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
209 Exported function (core API) for adding a new biblio to koha.
211 The first argument is a C<MARC::Record> object containing the
212 bib to add, while the second argument is the desired MARC
215 This function also accepts a third, optional argument: a hashref
216 to additional options. The only defined option is C<defer_marc_save>,
217 which if present and mapped to a true value, causes C<AddBiblio>
218 to omit the call to save the MARC in C<biblio_metadata.metadata>
219 This option is provided B<only>
220 for the use of scripts such as C<bulkmarcimport.pl> that may need
221 to do some manipulation of the MARC record for item parsing before
222 saving it and which cannot afford the performance hit of saving
223 the MARC record twice. Consequently, do not use that option
224 unless you can guarantee that C<ModBiblioMarc> will be called.
230 my $frameworkcode = shift;
231 my $options = @_ ? shift : undef;
232 my $defer_marc_save = 0;
234 carp('AddBiblio called with undefined record');
237 if ( defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'} ) {
238 $defer_marc_save = 1;
241 my ( $biblionumber, $biblioitemnumber, $error );
242 my $dbh = C4::Context->dbh;
244 # transform the data into koha-table style data
245 SetUTF8Flag($record);
246 my $olddata = TransformMarcToKoha( $record, $frameworkcode );
247 ( $biblionumber, $error ) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
248 $olddata->{'biblionumber'} = $biblionumber;
249 ( $biblioitemnumber, $error ) = _koha_add_biblioitem( $dbh, $olddata );
251 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
253 # update MARC subfield that stores biblioitems.cn_sort
254 _koha_marc_update_biblioitem_cn_sort( $record, $olddata, $frameworkcode );
257 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
259 # update OAI-PMH sets
260 if(C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
261 C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
264 logaction( "CATALOGUING", "ADD", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
265 return ( $biblionumber, $biblioitemnumber );
270 ModBiblio( $record,$biblionumber,$frameworkcode);
272 Replace an existing bib record identified by C<$biblionumber>
273 with one supplied by the MARC::Record object C<$record>. The embedded
274 item, biblioitem, and biblionumber fields from the previous
275 version of the bib record replace any such fields of those tags that
276 are present in C<$record>. Consequently, ModBiblio() is not
277 to be used to try to modify item records.
279 C<$frameworkcode> specifies the MARC framework to use
280 when storing the modified bib record; among other things,
281 this controls how MARC fields get mapped to display columns
282 in the C<biblio> and C<biblioitems> tables, as well as
283 which fields are used to store embedded item, biblioitem,
284 and biblionumber data for indexing.
286 Returns 1 on success 0 on failure
291 my ( $record, $biblionumber, $frameworkcode ) = @_;
293 carp 'No record passed to ModBiblio';
297 if ( C4::Context->preference("CataloguingLog") ) {
298 my $newrecord = GetMarcBiblio($biblionumber);
299 logaction( "CATALOGUING", "MODIFY", $biblionumber, "biblio BEFORE=>" . $newrecord->as_formatted );
302 # Cleaning up invalid fields must be done early or SetUTF8Flag is liable to
303 # throw an exception which probably won't be handled.
304 foreach my $field ($record->fields()) {
305 if (! $field->is_control_field()) {
306 if (scalar($field->subfields()) == 0 || (scalar($field->subfields()) == 1 && $field->subfield('9'))) {
307 $record->delete_field($field);
312 SetUTF8Flag($record);
313 my $dbh = C4::Context->dbh;
315 $frameworkcode = "" if !$frameworkcode || $frameworkcode eq "Default"; # XXX
317 _strip_item_fields($record, $frameworkcode);
319 # update biblionumber and biblioitemnumber in MARC
320 # FIXME - this is assuming a 1 to 1 relationship between
321 # biblios and biblioitems
322 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
323 $sth->execute($biblionumber);
324 my ($biblioitemnumber) = $sth->fetchrow;
326 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
328 # load the koha-table data object
329 my $oldbiblio = TransformMarcToKoha( $record, $frameworkcode );
331 # update MARC subfield that stores biblioitems.cn_sort
332 _koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode );
334 # update the MARC record (that now contains biblio and items) with the new record data
335 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
337 # modify the other koha tables
338 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
339 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
341 # update OAI-PMH sets
342 if(C4::Context->preference("OAI-PMH:AutoUpdateSets")) {
343 C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record);
349 =head2 _strip_item_fields
351 _strip_item_fields($record, $frameworkcode)
353 Utility routine to remove item tags from a
358 sub _strip_item_fields {
360 my $frameworkcode = shift;
361 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
362 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
364 # delete any item fields from incoming record to avoid
365 # duplication or incorrect data - use AddItem() or ModItem()
367 foreach my $field ( $record->field($itemtag) ) {
368 $record->delete_field($field);
374 my $error = &DelBiblio($biblionumber);
376 Exported function (core API) for deleting a biblio in koha.
377 Deletes biblio record from Zebra and Koha tables (biblio & biblioitems)
378 Also backs it up to deleted* tables.
379 Checks to make sure that the biblio has no items attached.
381 C<$error> : undef unless an error occurs
386 my ($biblionumber) = @_;
387 my $dbh = C4::Context->dbh;
388 my $error; # for error handling
390 # First make sure this biblio has no items attached
391 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
392 $sth->execute($biblionumber);
393 if ( my $itemnumber = $sth->fetchrow ) {
395 # Fix this to use a status the template can understand
396 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
399 return $error if $error;
401 # We delete attached subscriptions
403 my $subscriptions = C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
404 foreach my $subscription (@$subscriptions) {
405 C4::Serials::DelSubscription( $subscription->{subscriptionid} );
408 # We delete any existing holds
409 my $biblio = Koha::Biblios->find( $biblionumber );
410 my $holds = $biblio->holds;
411 require C4::Reserves;
412 while ( my $hold = $holds->next ) {
413 C4::Reserves::CancelReserve({ reserve_id => $hold->reserve_id }); # TODO Replace with $hold->cancel
416 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
417 # for at least 2 reasons :
418 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
419 # 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)
420 ModZebra( $biblionumber, "recordDelete", "biblioserver" );
422 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
423 $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
424 $sth->execute($biblionumber);
425 while ( my $biblioitemnumber = $sth->fetchrow ) {
427 # delete this biblioitem
428 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
429 return $error if $error;
433 # delete biblio from Koha tables and save in deletedbiblio
434 # must do this *after* _koha_delete_biblioitems, otherwise
435 # delete cascade will prevent deletedbiblioitems rows
436 # from being generated by _koha_delete_biblioitems
437 $error = _koha_delete_biblio( $dbh, $biblionumber );
439 logaction( "CATALOGUING", "DELETE", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
445 =head2 BiblioAutoLink
447 my $headings_linked = BiblioAutoLink($record, $frameworkcode)
449 Automatically links headings in a bib record to authorities.
451 Returns the number of headings changed
457 my $frameworkcode = shift;
459 carp('Undefined record passed to BiblioAutoLink');
462 my ( $num_headings_changed, %results );
465 "C4::Linker::" . ( C4::Context->preference("LinkerModule") || 'Default' );
466 unless ( can_load( modules => { $linker_module => undef } ) ) {
467 $linker_module = 'C4::Linker::Default';
468 unless ( can_load( modules => { $linker_module => undef } ) ) {
473 my $linker = $linker_module->new(
474 { 'options' => C4::Context->preference("LinkerOptions") } );
475 my ( $headings_changed, undef ) =
476 LinkBibHeadingsToAuthorities( $linker, $record, $frameworkcode, C4::Context->preference("CatalogModuleRelink") || '' );
477 # By default we probably don't want to relink things when cataloging
478 return $headings_changed;
481 =head2 LinkBibHeadingsToAuthorities
483 my $num_headings_changed, %results = LinkBibHeadingsToAuthorities($linker, $marc, $frameworkcode, [$allowrelink]);
485 Links bib headings to authority records by checking
486 each authority-controlled field in the C<MARC::Record>
487 object C<$marc>, looking for a matching authority record,
488 and setting the linking subfield $9 to the ID of that
491 If $allowrelink is false, existing authids will never be
492 replaced, regardless of the values of LinkerKeepStale and
495 Returns the number of heading links changed in the
500 sub LinkBibHeadingsToAuthorities {
503 my $frameworkcode = shift;
504 my $allowrelink = shift;
507 carp 'LinkBibHeadingsToAuthorities called on undefined bib record';
511 require C4::AuthoritiesMarc;
513 $allowrelink = 1 unless defined $allowrelink;
514 my $num_headings_changed = 0;
515 foreach my $field ( $bib->fields() ) {
516 my $heading = C4::Heading->new_from_bib_field( $field, $frameworkcode );
517 next unless defined $heading;
520 my $current_link = $field->subfield('9');
522 if ( defined $current_link && (!$allowrelink || !C4::Context->preference('LinkerRelink')) )
524 $results{'linked'}->{ $heading->display_form() }++;
528 my ( $authid, $fuzzy ) = $linker->get_link($heading);
530 $results{ $fuzzy ? 'fuzzy' : 'linked' }
531 ->{ $heading->display_form() }++;
532 next if defined $current_link and $current_link == $authid;
534 $field->delete_subfield( code => '9' ) if defined $current_link;
535 $field->add_subfields( '9', $authid );
536 $num_headings_changed++;
539 if ( defined $current_link
540 && (!$allowrelink || C4::Context->preference('LinkerKeepStale')) )
542 $results{'fuzzy'}->{ $heading->display_form() }++;
544 elsif ( C4::Context->preference('AutoCreateAuthorities') ) {
545 if ( _check_valid_auth_link( $current_link, $field ) ) {
546 $results{'linked'}->{ $heading->display_form() }++;
549 my $authority_type = Koha::Authority::Types->find( $heading->auth_type() );
550 my $marcrecordauth = MARC::Record->new();
551 if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
552 $marcrecordauth->leader(' nz a22 o 4500');
553 SetMarcUnicodeFlag( $marcrecordauth, 'MARC21' );
555 $field->delete_subfield( code => '9' )
556 if defined $current_link;
558 MARC::Field->new( $authority_type->auth_tag_to_report,
559 '', '', "a" => "" . $field->subfield('a') );
561 $authfield->add_subfields( $_->[0] => $_->[1] )
562 if ( $_->[0] =~ /[A-z]/ && $_->[0] ne "a" )
563 } $field->subfields();
564 $marcrecordauth->insert_fields_ordered($authfield);
566 # bug 2317: ensure new authority knows it's using UTF-8; currently
567 # only need to do this for MARC21, as MARC::Record->as_xml_record() handles
568 # automatically for UNIMARC (by not transcoding)
569 # FIXME: AddAuthority() instead should simply explicitly require that the MARC::Record
570 # use UTF-8, but as of 2008-08-05, did not want to introduce that kind
571 # of change to a core API just before the 3.0 release.
573 if ( C4::Context->preference('marcflavour') eq 'MARC21' ) {
574 $marcrecordauth->insert_fields_ordered(
577 'a' => "Machine generated authority record."
581 $bib->author() . ", "
582 . $bib->title_proper() . ", "
583 . $bib->publication_date() . " ";
584 $cite =~ s/^[\s\,]*//;
585 $cite =~ s/[\s\,]*$//;
588 . C4::Context->preference('MARCOrgCode') . ")"
589 . $bib->subfield( '999', 'c' ) . ": "
591 $marcrecordauth->insert_fields_ordered(
592 MARC::Field->new( '670', '', '', 'a' => $cite ) );
595 # warn "AUTH RECORD ADDED : ".$marcrecordauth->as_formatted;
598 C4::AuthoritiesMarc::AddAuthority( $marcrecordauth, '',
599 $heading->auth_type() );
600 $field->add_subfields( '9', $authid );
601 $num_headings_changed++;
602 $linker->update_cache($heading, $authid);
603 $results{'added'}->{ $heading->display_form() }++;
606 elsif ( defined $current_link ) {
607 if ( _check_valid_auth_link( $current_link, $field ) ) {
608 $results{'linked'}->{ $heading->display_form() }++;
611 $field->delete_subfield( code => '9' );
612 $num_headings_changed++;
613 $results{'unlinked'}->{ $heading->display_form() }++;
617 $results{'unlinked'}->{ $heading->display_form() }++;
622 return $num_headings_changed, \%results;
625 =head2 _check_valid_auth_link
627 if ( _check_valid_auth_link($authid, $field) ) {
631 Check whether the specified heading-auth link is valid without reference
632 to Zebra. Ideally this code would be in C4::Heading, but that won't be
633 possible until we have de-cycled C4::AuthoritiesMarc, so this is the
638 sub _check_valid_auth_link {
639 my ( $authid, $field ) = @_;
641 require C4::AuthoritiesMarc;
643 my $authorized_heading =
644 C4::AuthoritiesMarc::GetAuthorizedHeading( { 'authid' => $authid } ) || '';
646 return ($field->as_string('abcdefghijklmnopqrstuvwxyz') eq $authorized_heading);
649 =head2 GetRecordValue
651 my $values = GetRecordValue($field, $record, $frameworkcode);
653 Get MARC fields from a keyword defined in fieldmapping table.
658 my ( $field, $record, $frameworkcode ) = @_;
661 carp 'GetRecordValue called with undefined record';
664 my $dbh = C4::Context->dbh;
666 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
667 $sth->execute( $frameworkcode, $field );
671 while ( my $row = $sth->fetchrow_hashref ) {
672 foreach my $field ( $record->field( $row->{fieldcode} ) ) {
673 if ( ( $row->{subfieldcode} ne "" && $field->subfield( $row->{subfieldcode} ) ) ) {
674 foreach my $subfield ( $field->subfield( $row->{subfieldcode} ) ) {
675 push @result, { 'subfield' => $subfield };
678 } elsif ( $row->{subfieldcode} eq "" ) {
679 push @result, { 'subfield' => $field->as_string() };
689 $data = &GetBiblioData($biblionumber);
691 Returns information about the book with the given biblionumber.
692 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
693 the C<biblio> and C<biblioitems> tables in the
696 In addition, C<$data-E<gt>{subject}> is the list of the book's
697 subjects, separated by C<" , "> (space, comma, space).
698 If there are multiple biblioitems with the given biblionumber, only
699 the first one is considered.
705 my $dbh = C4::Context->dbh;
707 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
709 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
710 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
711 WHERE biblio.biblionumber = ?";
713 my $sth = $dbh->prepare($query);
714 $sth->execute($bibnum);
716 $data = $sth->fetchrow_hashref;
720 } # sub GetBiblioData
722 =head2 &GetBiblioItemData
724 $itemdata = &GetBiblioItemData($biblioitemnumber);
726 Looks up the biblioitem with the given biblioitemnumber. Returns a
727 reference-to-hash. The keys are the fields from the C<biblio>,
728 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
729 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
734 sub GetBiblioItemData {
735 my ($biblioitemnumber) = @_;
736 my $dbh = C4::Context->dbh;
737 my $query = "SELECT *,biblioitems.notes AS bnotes
738 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
739 unless ( C4::Context->preference('item-level_itypes') ) {
740 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
742 $query .= " WHERE biblioitemnumber = ? ";
743 my $sth = $dbh->prepare($query);
745 $sth->execute($biblioitemnumber);
746 $data = $sth->fetchrow_hashref;
749 } # sub &GetBiblioItemData
751 =head2 GetBiblioItemByBiblioNumber
753 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
757 sub GetBiblioItemByBiblioNumber {
758 my ($biblionumber) = @_;
759 my $dbh = C4::Context->dbh;
760 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
764 $sth->execute($biblionumber);
766 while ( my $data = $sth->fetchrow_hashref ) {
767 push @results, $data;
776 $isbd = &GetISBDView({
777 'record' => $marc_record,
778 'template' => $interface, # opac/intranet
779 'framework' => $framework,
782 Return the ISBD view which can be included in opac and intranet
789 # Expecting record WITH items.
790 my $record = $params->{record};
791 return unless defined $record;
793 my $template = $params->{template} // q{};
794 my $sysprefname = $template eq 'opac' ? 'opacisbd' : 'isbd';
795 my $framework = $params->{framework};
796 my $itemtype = $framework;
797 my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch", $itemtype );
798 my $tagslib = &GetMarcStructure( 1, $itemtype, { unsafe => 1 } );
800 my $ISBD = C4::Context->preference($sysprefname);
805 foreach my $isbdfield ( split( /#/, $bloc ) ) {
807 # $isbdfield= /(.?.?.?)/;
808 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
809 my $fieldvalue = $1 || 0;
810 my $subfvalue = $2 || "";
812 my $analysestring = $4;
815 # warn "==> $1 / $2 / $3 / $4";
816 # my $fieldvalue=substr($isbdfield,0,3);
817 if ( $fieldvalue > 0 ) {
818 my $hasputtextbefore = 0;
819 my @fieldslist = $record->field($fieldvalue);
820 @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf );
822 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
823 # warn "FV : $fieldvalue";
824 if ( $subfvalue ne "" ) {
825 # OPAC hidden subfield
827 if ( ( $template eq 'opac' )
828 && ( $tagslib->{$fieldvalue}->{$subfvalue}->{'hidden'} || 0 ) > 0 );
829 foreach my $field (@fieldslist) {
830 foreach my $subfield ( $field->subfield($subfvalue) ) {
831 my $calculated = $analysestring;
832 my $tag = $field->tag();
835 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib );
836 my $tagsubf = $tag . $subfvalue;
837 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
838 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
840 # field builded, store the result
841 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
842 $blocres .= $textbefore;
843 $hasputtextbefore = 1;
846 # remove punctuation at start
847 $calculated =~ s/^( |;|:|\.|-)*//g;
848 $blocres .= $calculated;
853 $blocres .= $textafter if $hasputtextbefore;
855 foreach my $field (@fieldslist) {
856 my $calculated = $analysestring;
857 my $tag = $field->tag();
860 my @subf = $field->subfields;
861 for my $i ( 0 .. $#subf ) {
862 my $valuecode = $subf[$i][1];
863 my $subfieldcode = $subf[$i][0];
864 # OPAC hidden subfield
866 if ( ( $template eq 'opac' )
867 && ( $tagslib->{$fieldvalue}->{$subfieldcode}->{'hidden'} || 0 ) > 0 );
868 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib );
869 my $tagsubf = $tag . $subfieldcode;
871 $calculated =~ s/ # replace all {{}} codes by the value code.
872 \{\{$tagsubf\}\} # catch the {{actualcode}}
874 $valuecode # replace by the value code
877 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
878 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
881 # field builded, store the result
882 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
883 $blocres .= $textbefore;
884 $hasputtextbefore = 1;
887 # remove punctuation at start
888 $calculated =~ s/^( |;|:|\.|-)*//g;
889 $blocres .= $calculated;
892 $blocres .= $textafter if $hasputtextbefore;
895 $blocres .= $isbdfield;
900 $res =~ s/\{(.*?)\}//g;
902 $res =~ s/\n/<br\/>/g;
912 my $biblio = &GetBiblio($biblionumber);
917 my ($biblionumber) = @_;
918 my $dbh = C4::Context->dbh;
919 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
922 $sth->execute($biblionumber);
923 if ( my $data = $sth->fetchrow_hashref ) {
929 =head2 GetBiblioItemInfosOf
931 GetBiblioItemInfosOf(@biblioitemnumbers);
935 sub GetBiblioItemInfosOf {
936 my @biblioitemnumbers = @_;
938 my $biblioitemnumber_values = @biblioitemnumbers ? join( ',', @biblioitemnumbers ) : "''";
940 my $dbh = C4::Context->dbh;
942 SELECT biblioitemnumber,
946 WHERE biblioitemnumber IN ($biblioitemnumber_values)
948 return $dbh->selectall_hashref($query, 'biblioitemnumber');
951 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
953 =head2 IsMarcStructureInternal
955 my $tagslib = C4::Biblio::GetMarcStructure();
956 for my $tag ( sort keys %$tagslib ) {
958 for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
959 next if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
964 GetMarcStructure creates keys (lib, tab, mandatory, repeatable) for a display purpose.
965 These different values should not be processed as valid subfields.
969 sub IsMarcStructureInternal {
970 my ( $subfield ) = @_;
971 return ref $subfield ? 0 : 1;
974 =head2 GetMarcStructure
976 $res = GetMarcStructure($forlibrarian, $frameworkcode, [ $params ]);
978 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
979 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
980 $frameworkcode : the framework code to read
981 $params allows you to pass { unsafe => 1 } for better performance.
983 Note: If you call GetMarcStructure with unsafe => 1, do not modify or
984 even autovivify its contents. It is a cached/shared data structure. Your
985 changes c/would be passed around in subsequent calls.
989 sub GetMarcStructure {
990 my ( $forlibrarian, $frameworkcode, $params ) = @_;
991 $frameworkcode = "" unless $frameworkcode;
993 $forlibrarian = $forlibrarian ? 1 : 0;
994 my $unsafe = ($params && $params->{unsafe})? 1: 0;
995 my $cache = Koha::Caches->get_instance();
996 my $cache_key = "MarcStructure-$forlibrarian-$frameworkcode";
997 my $cached = $cache->get_from_cache($cache_key, { unsafe => $unsafe });
998 return $cached if $cached;
1000 my $dbh = C4::Context->dbh;
1001 my $sth = $dbh->prepare(
1002 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
1003 FROM marc_tag_structure
1004 WHERE frameworkcode=?
1007 $sth->execute($frameworkcode);
1008 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
1010 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
1011 $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1012 $res->{$tag}->{tab} = "";
1013 $res->{$tag}->{mandatory} = $mandatory;
1014 $res->{$tag}->{repeatable} = $repeatable;
1017 $sth = $dbh->prepare(
1018 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue,maxlength
1019 FROM marc_subfield_structure
1020 WHERE frameworkcode=?
1021 ORDER BY tagfield,tagsubfield
1025 $sth->execute($frameworkcode);
1028 my $authorised_value;
1040 ( $tag, $subfield, $liblibrarian, $libopac, $tab, $mandatory, $repeatable, $authorised_value,
1041 $authtypecode, $value_builder, $kohafield, $seealso, $hidden, $isurl, $link, $defaultvalue,
1046 $res->{$tag}->{$subfield}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1047 $res->{$tag}->{$subfield}->{tab} = $tab;
1048 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1049 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1050 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1051 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1052 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1053 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1054 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1055 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1056 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1057 $res->{$tag}->{$subfield}->{'link'} = $link;
1058 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1059 $res->{$tag}->{$subfield}->{maxlength} = $maxlength;
1062 $cache->set_in_cache($cache_key, $res);
1066 =head2 GetUsedMarcStructure
1068 The same function as GetMarcStructure except it just takes field
1069 in tab 0-9. (used field)
1071 my $results = GetUsedMarcStructure($frameworkcode);
1073 C<$results> is a ref to an array which each case containts a ref
1074 to a hash which each keys is the columns from marc_subfield_structure
1076 C<$frameworkcode> is the framework code.
1080 sub GetUsedMarcStructure {
1081 my $frameworkcode = shift || '';
1084 FROM marc_subfield_structure
1086 AND frameworkcode = ?
1087 ORDER BY tagfield, tagsubfield
1089 my $sth = C4::Context->dbh->prepare($query);
1090 $sth->execute($frameworkcode);
1091 return $sth->fetchall_arrayref( {} );
1094 =head2 GetMarcSubfieldStructure
1098 sub GetMarcSubfieldStructure {
1099 my ( $frameworkcode ) = @_;
1101 $frameworkcode //= '';
1103 my $cache = Koha::Caches->get_instance();
1104 my $cache_key = "MarcSubfieldStructure-$frameworkcode";
1105 my $cached = $cache->get_from_cache($cache_key);
1106 return $cached if $cached;
1108 my $dbh = C4::Context->dbh;
1109 my $subfield_structure = $dbh->selectall_hashref( q|
1111 FROM marc_subfield_structure
1112 WHERE frameworkcode = ?
1114 |, 'kohafield', {}, $frameworkcode );
1116 $cache->set_in_cache( $cache_key, $subfield_structure );
1117 return $subfield_structure;
1120 =head2 GetMarcFromKohaField
1122 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1124 Returns the MARC fields & subfields mapped to the koha field
1125 for the given frameworkcode or default framework if $frameworkcode is missing
1129 sub GetMarcFromKohaField {
1130 my ( $kohafield, $frameworkcode ) = @_;
1131 return (0, undef) unless $kohafield;
1132 my $mss = GetMarcSubfieldStructure( $frameworkcode );
1133 return ( $mss->{$kohafield}{tagfield}, $mss->{$kohafield}{tagsubfield} );
1136 =head2 GetMarcSubfieldStructureFromKohaField
1138 my $subfield_structure = &GetMarcSubfieldStructureFromKohaField($kohafield, $frameworkcode);
1140 Returns a hashref where keys are marc_subfield_structure column names for the
1141 row where kohafield=$kohafield for the given framework code.
1143 $frameworkcode is optional. If not given, then the default framework is used.
1147 sub GetMarcSubfieldStructureFromKohaField {
1148 my ( $kohafield, $frameworkcode ) = @_;
1150 return unless $kohafield;
1152 my $mss = GetMarcSubfieldStructure( $frameworkcode );
1153 return exists $mss->{$kohafield}
1154 ? $mss->{$kohafield}
1158 =head2 GetMarcBiblio
1160 my $record = GetMarcBiblio($biblionumber, [$embeditems], [$opac]);
1162 Returns MARC::Record representing a biblio record, or C<undef> if the
1163 biblionumber doesn't exist.
1167 =item C<$biblionumber>
1171 =item C<$embeditems>
1173 set to true to include item information.
1177 set to true to make the result suited for OPAC view. This causes things like
1178 OpacHiddenItems to be applied.
1185 my $biblionumber = shift;
1186 my $embeditems = shift || 0;
1187 my $opac = shift || 0;
1189 if (not defined $biblionumber) {
1190 carp 'GetMarcBiblio called with undefined biblionumber';
1194 my $dbh = C4::Context->dbh;
1195 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=? ");
1196 $sth->execute($biblionumber);
1197 my $row = $sth->fetchrow_hashref;
1198 my $biblioitemnumber = $row->{'biblioitemnumber'};
1199 my $marcxml = GetXmlBiblio( $biblionumber );
1200 $marcxml = StripNonXmlChars( $marcxml );
1201 my $frameworkcode = GetFrameworkCode($biblionumber);
1202 MARC::File::XML->default_record_format( C4::Context->preference('marcflavour') );
1203 my $record = MARC::Record->new();
1207 MARC::Record::new_from_xml( $marcxml, "utf8",
1208 C4::Context->preference('marcflavour') );
1210 if ($@) { warn " problem with :$biblionumber : $@ \n$marcxml"; }
1211 return unless $record;
1213 C4::Biblio::_koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber,
1214 $biblioitemnumber );
1215 C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, undef, $opac )
1227 my $marcxml = GetXmlBiblio($biblionumber);
1229 Returns biblio_metadata.metadata/marcxml of the biblionumber passed in parameter.
1230 The XML should only contain biblio information (item information is no longer stored in marcxml field)
1235 my ($biblionumber) = @_;
1236 my $dbh = C4::Context->dbh;
1237 return unless $biblionumber;
1238 my ($marcxml) = $dbh->selectrow_array(
1241 FROM biblio_metadata
1242 WHERE biblionumber=?
1243 AND format='marcxml'
1245 |, undef, $biblionumber, C4::Context->preference('marcflavour')
1250 =head2 GetCOinSBiblio
1252 my $coins = GetCOinSBiblio($record);
1254 Returns the COinS (a span) which can be included in a biblio record
1258 sub GetCOinSBiblio {
1261 # get the coin format
1263 carp 'GetCOinSBiblio called with undefined record';
1266 my $pos7 = substr $record->leader(), 7, 1;
1267 my $pos6 = substr $record->leader(), 6, 1;
1270 my ( $aulast, $aufirst ) = ( '', '' );
1279 my $titletype = 'b';
1281 # For the purposes of generating COinS metadata, LDR/06-07 can be
1282 # considered the same for UNIMARC and MARC21
1287 'b' => 'manuscript',
1289 'd' => 'manuscript',
1293 'i' => 'audioRecording',
1294 'j' => 'audioRecording',
1297 'm' => 'computerProgram',
1302 'a' => 'journalArticle',
1306 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
1308 if ( $genre eq 'book' ) {
1309 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1312 ##### We must transform mtx to a valable mtx and document type ####
1313 if ( $genre eq 'book' ) {
1315 } elsif ( $genre eq 'journal' ) {
1318 } elsif ( $genre eq 'journalArticle' ) {
1326 $genre = ( $mtx eq 'dc' ) ? "&rft.type=$genre" : "&rft.genre=$genre";
1328 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
1331 $aulast = $record->subfield( '700', 'a' ) || '';
1332 $aufirst = $record->subfield( '700', 'b' ) || '';
1333 $oauthors = "&rft.au=$aufirst $aulast";
1336 if ( $record->field('200') ) {
1337 for my $au ( $record->field('200')->subfield('g') ) {
1338 $oauthors .= "&rft.au=$au";
1343 ? "&rft.title=" . $record->subfield( '200', 'a' )
1344 : "&rft.title=" . $record->subfield( '200', 'a' ) . "&rft.btitle=" . $record->subfield( '200', 'a' );
1345 $pubyear = $record->subfield( '210', 'd' ) || '';
1346 $publisher = $record->subfield( '210', 'c' ) || '';
1347 $isbn = $record->subfield( '010', 'a' ) || '';
1348 $issn = $record->subfield( '011', 'a' ) || '';
1351 # MARC21 need some improve
1354 if ( $record->field('100') ) {
1355 $oauthors .= "&rft.au=" . $record->subfield( '100', 'a' );
1359 if ( $record->field('700') ) {
1360 for my $au ( $record->field('700')->subfield('a') ) {
1361 $oauthors .= "&rft.au=$au";
1364 $title = "&rft." . $titletype . "title=" . $record->subfield( '245', 'a' );
1365 $subtitle = $record->subfield( '245', 'b' ) || '';
1366 $title .= $subtitle;
1367 if ($titletype eq 'a') {
1368 $pubyear = $record->field('008') || '';
1369 $pubyear = substr($pubyear->data(), 7, 4) if $pubyear;
1370 $isbn = $record->subfield( '773', 'z' ) || '';
1371 $issn = $record->subfield( '773', 'x' ) || '';
1372 if ($mtx eq 'journal') {
1373 $title .= "&rft.title=" . (($record->subfield( '773', 't' ) || $record->subfield( '773', 'a')));
1375 $title .= "&rft.btitle=" . (($record->subfield( '773', 't' ) || $record->subfield( '773', 'a')) || '');
1377 foreach my $rel ($record->subfield( '773', 'g' )) {
1384 $pubyear = $record->subfield( '260', 'c' ) || '';
1385 $publisher = $record->subfield( '260', 'b' ) || '';
1386 $isbn = $record->subfield( '020', 'a' ) || '';
1387 $issn = $record->subfield( '022', 'a' ) || '';
1392 "ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3A$mtx$genre$title&rft.isbn=$isbn&rft.issn=$issn&rft.aulast=$aulast&rft.aufirst=$aufirst$oauthors&rft.pub=$publisher&rft.date=$pubyear&rft.pages=$pages";
1393 $coins_value =~ s/(\ |&[^a])/\+/g;
1394 $coins_value =~ s/\"/\"\;/g;
1396 #<!-- TMPL_VAR NAME="ocoins_format" -->&rft.au=<!-- TMPL_VAR NAME="author" -->&rft.btitle=<!-- TMPL_VAR NAME="title" -->&rft.date=<!-- TMPL_VAR NAME="publicationyear" -->&rft.pages=<!-- TMPL_VAR NAME="pages" -->&rft.isbn=<!-- TMPL_VAR NAME=amazonisbn -->&rft.aucorp=&rft.place=<!-- TMPL_VAR NAME="place" -->&rft.pub=<!-- TMPL_VAR NAME="publishercode" -->&rft.edition=<!-- TMPL_VAR NAME="edition" -->&rft.series=<!-- TMPL_VAR NAME="series" -->&rft.genre="
1398 return $coins_value;
1404 return the prices in accordance with the Marc format.
1406 returns 0 if no price found
1407 returns undef if called without a marc record or with
1408 an unrecognized marc format
1413 my ( $record, $marcflavour ) = @_;
1415 carp 'GetMarcPrice called on undefined record';
1422 if ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) {
1423 @listtags = ('345', '020');
1425 } elsif ( $marcflavour eq "UNIMARC" ) {
1426 @listtags = ('345', '010');
1432 for my $field ( $record->field(@listtags) ) {
1433 for my $subfield_value ($field->subfield($subfield)){
1435 $subfield_value = MungeMarcPrice( $subfield_value );
1436 return $subfield_value if ($subfield_value);
1439 return 0; # no price found
1442 =head2 MungeMarcPrice
1444 Return the best guess at what the actual price is from a price field.
1448 sub MungeMarcPrice {
1450 return unless ( $price =~ m/\d/ ); ## No digits means no price.
1451 # Look for the currency symbol and the normalized code of the active currency, if it's there,
1452 my $active_currency = Koha::Acquisition::Currencies->get_active;
1453 my $symbol = $active_currency->symbol;
1454 my $isocode = $active_currency->isocode;
1455 $isocode = $active_currency->currency unless defined $isocode;
1458 my @matches =($price=~ /
1460 ( # start of capturing parenthesis
1462 (?:[\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'
1463 |(?:\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'
1465 \s?\p{Sc}?\s? # followed or not by a whitespace. \p{Sc}?\s? are for cases like '25$ USD'
1467 (?:[\p{Sc}\p{L}\/.]){1,4} # followed by same block as symbol block
1468 |(?:\d+[\p{P}\s]?){1,4} # or by same block as digits block
1470 \s?\p{L}{0,4}\s? # followed or not by a whitespace. \p{L}{0,4}\s? are for cases like '$9.50 USD'
1471 ) # end of capturing parenthesis
1472 (?:\p{P}|\z) # followed by a punctuation sign or by the end of the string
1476 foreach ( @matches ) {
1477 $localprice = $_ and last if index($_, $isocode)>=0;
1479 if ( !$localprice ) {
1480 foreach ( @matches ) {
1481 $localprice = $_ and last if $_=~ /(^|[^\p{Sc}\p{L}\/])\Q$symbol\E([^\p{Sc}\p{L}\/]+\z|\z)/;
1486 if ( $localprice ) {
1487 $price = $localprice;
1489 ## Grab the first number in the string ( can use commas or periods for thousands separator and/or decimal separator )
1490 ( $price ) = $price =~ m/([\d\,\.]+[[\,\.]\d\d]?)/;
1492 # eliminate symbol/isocode, space and any final dot from the string
1493 $price =~ s/[\p{Sc}\p{L}\/ ]|\.$//g;
1494 # remove comma,dot when used as separators from hundreds
1495 $price =~s/[\,\.](\d{3})/$1/g;
1496 # convert comma to dot to ensure correct display of decimals if existing
1502 =head2 GetMarcQuantity
1504 return the quantity of a book. Used in acquisition only, when importing a file an iso2709 from a bookseller
1505 Warning : this is not really in the marc standard. In Unimarc, Electre (the most widely used bookseller) use the 969$a
1507 returns 0 if no quantity found
1508 returns undef if called without a marc record or with
1509 an unrecognized marc format
1513 sub GetMarcQuantity {
1514 my ( $record, $marcflavour ) = @_;
1516 carp 'GetMarcQuantity called on undefined record';
1523 if ( $marcflavour eq "MARC21" ) {
1525 } elsif ( $marcflavour eq "UNIMARC" ) {
1526 @listtags = ('969');
1532 for my $field ( $record->field(@listtags) ) {
1533 for my $subfield_value ($field->subfield($subfield)){
1535 if ($subfield_value) {
1536 # in France, the cents separator is the , but sometimes, ppl use a .
1537 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
1538 $subfield_value =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
1539 return $subfield_value;
1543 return 0; # no price found
1547 =head2 GetAuthorisedValueDesc
1549 my $subfieldvalue =get_authorised_value_desc(
1550 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category, $opac);
1552 Retrieve the complete description for a given authorised value.
1554 Now takes $category and $value pair too.
1556 my $auth_value_desc =GetAuthorisedValueDesc(
1557 '','', 'DVD' ,'','','CCODE');
1559 If the optional $opac parameter is set to a true value, displays OPAC
1560 descriptions rather than normal ones when they exist.
1564 sub GetAuthorisedValueDesc {
1565 my ( $tag, $subfield, $value, $framework, $tagslib, $category, $opac ) = @_;
1569 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1572 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1573 return Koha::Libraries->find($value)->branchname;
1577 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1578 my $itemtype = Koha::ItemTypes->find( $value );
1579 return $itemtype ? $itemtype->translated_description : q||;
1582 #---- "true" authorized value
1583 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1586 my $dbh = C4::Context->dbh;
1587 if ( $category ne "" ) {
1588 my $sth = $dbh->prepare( "SELECT lib, lib_opac FROM authorised_values WHERE category = ? AND authorised_value = ?" );
1589 $sth->execute( $category, $value );
1590 my $data = $sth->fetchrow_hashref;
1591 return ( $opac && $data->{'lib_opac'} ) ? $data->{'lib_opac'} : $data->{'lib'};
1593 return $value; # if nothing is found return the original value
1597 =head2 GetMarcControlnumber
1599 $marccontrolnumber = GetMarcControlnumber($record,$marcflavour);
1601 Get the control number / record Identifier from the MARC record and return it.
1605 sub GetMarcControlnumber {
1606 my ( $record, $marcflavour ) = @_;
1608 carp 'GetMarcControlnumber called on undefined record';
1611 my $controlnumber = "";
1612 # Control number or Record identifier are the same field in MARC21, UNIMARC and NORMARC
1613 # Keep $marcflavour for possible later use
1614 if ($marcflavour eq "MARC21" || $marcflavour eq "UNIMARC" || $marcflavour eq "NORMARC") {
1615 my $controlnumberField = $record->field('001');
1616 if ($controlnumberField) {
1617 $controlnumber = $controlnumberField->data();
1620 return $controlnumber;
1625 $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
1627 Get all ISBNs from the MARC record and returns them in an array.
1628 ISBNs stored in different fields depending on MARC flavour
1633 my ( $record, $marcflavour ) = @_;
1635 carp 'GetMarcISBN called on undefined record';
1639 if ( $marcflavour eq "UNIMARC" ) {
1641 } else { # assume marc21 if not unimarc
1646 foreach my $field ( $record->field($scope) ) {
1647 my $isbn = $field->subfield( 'a' );
1648 if ( $isbn ne "" ) {
1649 push @marcisbns, $isbn;
1659 $marcissnsarray = GetMarcISSN( $record, $marcflavour );
1661 Get all valid ISSNs from the MARC record and returns them in an array.
1662 ISSNs are stored in different fields depending on MARC flavour
1667 my ( $record, $marcflavour ) = @_;
1669 carp 'GetMarcISSN called on undefined record';
1673 if ( $marcflavour eq "UNIMARC" ) {
1676 else { # assume MARC21 or NORMARC
1680 foreach my $field ( $record->field($scope) ) {
1681 push @marcissns, $field->subfield( 'a' )
1682 if ( $field->subfield( 'a' ) ne "" );
1689 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1691 Get all notes from the MARC record and returns them in an array.
1692 The notes are stored in different fields depending on MARC flavour.
1693 MARC21 field 555 gets special attention for the $u subfields.
1698 my ( $record, $marcflavour ) = @_;
1700 carp 'GetMarcNotes called on undefined record';
1704 my $scope = $marcflavour eq "UNIMARC"? '3..': '5..';
1706 my %blacklist = map { $_ => 1 }
1707 split( /,/, C4::Context->preference('NotesBlacklist'));
1708 foreach my $field ( $record->field($scope) ) {
1709 my $tag = $field->tag();
1710 next if $blacklist{ $tag };
1711 if( $marcflavour ne 'UNIMARC' && $tag =~ /555/ ) {
1712 # Field 555$u contains URLs
1713 # We first push the regular subfields and all $u's separately
1714 # Leave further actions to the template
1715 push @marcnotes, { marcnote => $field->as_string('abcd') };
1716 foreach my $sub ( $field->subfield('u') ) {
1717 push @marcnotes, { marcnote => $sub };
1720 push @marcnotes, { marcnote => $field->as_string() };
1726 =head2 GetMarcSubjects
1728 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1730 Get all subjects from the MARC record and returns them in an array.
1731 The subjects are stored in different fields depending on MARC flavour
1735 sub GetMarcSubjects {
1736 my ( $record, $marcflavour ) = @_;
1738 carp 'GetMarcSubjects called on undefined record';
1741 my ( $mintag, $maxtag, $fields_filter );
1742 if ( $marcflavour eq "UNIMARC" ) {
1745 $fields_filter = '6..';
1746 } else { # marc21/normarc
1749 $fields_filter = '6..';
1754 my $subject_limit = C4::Context->preference("TraceCompleteSubfields") ? 'su,complete-subfield' : 'su';
1755 my $AuthoritySeparator = C4::Context->preference('AuthoritySeparator');
1757 foreach my $field ( $record->field($fields_filter) ) {
1758 next unless ($field->tag() >= $mintag && $field->tag() <= $maxtag);
1760 my @subfields = $field->subfields();
1763 # if there is an authority link, build the links with an= subfield9
1764 my $subfield9 = $field->subfield('9');
1767 my $linkvalue = $subfield9;
1768 $linkvalue =~ s/(\(|\))//g;
1769 @link_loop = ( { limit => 'an', 'link' => $linkvalue } );
1770 $authoritylink = $linkvalue
1774 for my $subject_subfield (@subfields) {
1775 next if ( $subject_subfield->[0] eq '9' );
1777 # don't load unimarc subfields 3,4,5
1778 next if ( ( $marcflavour eq "UNIMARC" ) and ( $subject_subfield->[0] =~ /2|3|4|5/ ) );
1779 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1780 next if ( ( $marcflavour eq "MARC21" ) and ( $subject_subfield->[0] =~ /2/ ) );
1782 my $code = $subject_subfield->[0];
1783 my $value = $subject_subfield->[1];
1784 my $linkvalue = $value;
1785 $linkvalue =~ s/(\(|\))//g;
1786 # if no authority link, build a search query
1787 unless ($subfield9) {
1789 limit => $subject_limit,
1790 'link' => $linkvalue,
1791 operator => (scalar @link_loop) ? ' and ' : undef
1794 my @this_link_loop = @link_loop;
1796 unless ( $code eq '0' ) {
1797 push @subfields_loop, {
1800 link_loop => \@this_link_loop,
1801 separator => (scalar @subfields_loop) ? $AuthoritySeparator : ''
1806 push @marcsubjects, {
1807 MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop,
1808 authoritylink => $authoritylink,
1809 } if $authoritylink || @subfields_loop;
1812 return \@marcsubjects;
1813 } #end getMARCsubjects
1815 =head2 GetMarcAuthors
1817 authors = GetMarcAuthors($record,$marcflavour);
1819 Get all authors from the MARC record and returns them in an array.
1820 The authors are stored in different fields depending on MARC flavour
1824 sub GetMarcAuthors {
1825 my ( $record, $marcflavour ) = @_;
1827 carp 'GetMarcAuthors called on undefined record';
1830 my ( $mintag, $maxtag, $fields_filter );
1832 # tagslib useful only for UNIMARC author responsibilities
1834 if ( $marcflavour eq "UNIMARC" ) {
1835 # FIXME : we don't have the framework available, we take the default framework. May be buggy on some setups, will be usually correct.
1836 $tagslib = GetMarcStructure( 1, '', { unsafe => 1 });
1839 $fields_filter = '7..';
1840 } else { # marc21/normarc
1843 $fields_filter = '7..';
1847 my $AuthoritySeparator = C4::Context->preference('AuthoritySeparator');
1849 foreach my $field ( $record->field($fields_filter) ) {
1850 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1853 my @subfields = $field->subfields();
1856 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1857 my $subfield9 = $field->subfield('9');
1859 my $linkvalue = $subfield9;
1860 $linkvalue =~ s/(\(|\))//g;
1861 @link_loop = ( { 'limit' => 'an', 'link' => $linkvalue } );
1866 for my $authors_subfield (@subfields) {
1867 next if ( $authors_subfield->[0] eq '9' );
1869 # unimarc3 contains the $3 of the author for UNIMARC.
1870 # For french academic libraries, it's the "ppn", and it's required for idref webservice
1871 $unimarc3 = $authors_subfield->[1] if $marcflavour eq 'UNIMARC' and $authors_subfield->[0] =~ /3/;
1873 # don't load unimarc subfields 3, 5
1874 next if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /3|5/ ) );
1876 my $code = $authors_subfield->[0];
1877 my $value = $authors_subfield->[1];
1878 my $linkvalue = $value;
1879 $linkvalue =~ s/(\(|\))//g;
1880 # UNIMARC author responsibility
1881 if ( $marcflavour eq 'UNIMARC' and $code eq '4' ) {
1882 $value = GetAuthorisedValueDesc( $field->tag(), $code, $value, '', $tagslib );
1883 $linkvalue = "($value)";
1885 # if no authority link, build a search query
1886 unless ($subfield9) {
1889 'link' => $linkvalue,
1890 operator => (scalar @link_loop) ? ' and ' : undef
1893 my @this_link_loop = @link_loop;
1895 unless ( $code eq '0') {
1896 push @subfields_loop, {
1897 tag => $field->tag(),
1900 link_loop => \@this_link_loop,
1901 separator => (scalar @subfields_loop) ? $AuthoritySeparator : ''
1905 push @marcauthors, {
1906 MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop,
1907 authoritylink => $subfield9,
1908 unimarc3 => $unimarc3
1911 return \@marcauthors;
1916 $marcurls = GetMarcUrls($record,$marcflavour);
1918 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1919 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1924 my ( $record, $marcflavour ) = @_;
1926 carp 'GetMarcUrls called on undefined record';
1931 for my $field ( $record->field('856') ) {
1933 for my $note ( $field->subfield('z') ) {
1934 push @notes, { note => $note };
1936 my @urls = $field->subfield('u');
1937 foreach my $url (@urls) {
1938 $url =~ s/^\s+|\s+$//g; # trim
1940 if ( $marcflavour eq 'MARC21' ) {
1941 my $s3 = $field->subfield('3');
1942 my $link = $field->subfield('y');
1943 unless ( $url =~ /^\w+:/ ) {
1944 if ( $field->indicator(1) eq '7' ) {
1945 $url = $field->subfield('2') . "://" . $url;
1946 } elsif ( $field->indicator(1) eq '1' ) {
1947 $url = 'ftp://' . $url;
1950 # properly, this should be if ind1=4,
1951 # however we will assume http protocol since we're building a link.
1952 $url = 'http://' . $url;
1956 # TODO handle ind 2 (relationship)
1961 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1962 $marcurl->{'part'} = $s3 if ($link);
1963 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1965 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1966 $marcurl->{'MARCURL'} = $url;
1968 push @marcurls, $marcurl;
1974 =head2 GetMarcSeries
1976 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1978 Get all series from the MARC record and returns them in an array.
1979 The series are stored in different fields depending on MARC flavour
1984 my ( $record, $marcflavour ) = @_;
1986 carp 'GetMarcSeries called on undefined record';
1990 my ( $mintag, $maxtag, $fields_filter );
1991 if ( $marcflavour eq "UNIMARC" ) {
1994 $fields_filter = '2..';
1995 } else { # marc21/normarc
1998 $fields_filter = '4..';
2002 my $AuthoritySeparator = C4::Context->preference('AuthoritySeparator');
2004 foreach my $field ( $record->field($fields_filter) ) {
2005 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
2007 my @subfields = $field->subfields();
2010 for my $series_subfield (@subfields) {
2012 # ignore $9, used for authority link
2013 next if ( $series_subfield->[0] eq '9' );
2016 my $code = $series_subfield->[0];
2017 my $value = $series_subfield->[1];
2018 my $linkvalue = $value;
2019 $linkvalue =~ s/(\(|\))//g;
2021 # see if this is an instance of a volume
2022 if ( $code eq 'v' ) {
2027 'link' => $linkvalue,
2028 operator => (scalar @link_loop) ? ' and ' : undef
2031 if ($volume_number) {
2032 push @subfields_loop, { volumenum => $value };
2034 push @subfields_loop, {
2037 link_loop => \@link_loop,
2038 separator => (scalar @subfields_loop) ? $AuthoritySeparator : '',
2039 volumenum => $volume_number,
2043 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
2046 return \@marcseries;
2047 } #end getMARCseriess
2051 $marchostsarray = GetMarcHosts($record,$marcflavour);
2053 Get all host records (773s MARC21, 461 UNIMARC) from the MARC record and returns them in an array.
2058 my ( $record, $marcflavour ) = @_;
2060 carp 'GetMarcHosts called on undefined record';
2064 my ( $tag,$title_subf,$bibnumber_subf,$itemnumber_subf);
2065 $marcflavour ||="MARC21";
2066 if ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) {
2069 $bibnumber_subf ="0";
2070 $itemnumber_subf='9';
2072 elsif ($marcflavour eq "UNIMARC") {
2075 $bibnumber_subf ="0";
2076 $itemnumber_subf='9';
2081 foreach my $field ( $record->field($tag)) {
2085 my $hostbiblionumber = $field->subfield("$bibnumber_subf");
2086 my $hosttitle = $field->subfield($title_subf);
2087 my $hostitemnumber=$field->subfield($itemnumber_subf);
2088 push @fields_loop, { hostbiblionumber => $hostbiblionumber, hosttitle => $hosttitle, hostitemnumber => $hostitemnumber};
2089 push @marchosts, { MARCHOSTS_FIELDS_LOOP => \@fields_loop };
2092 my $marchostsarray = \@marchosts;
2093 return $marchostsarray;
2096 =head2 UpsertMarcSubfield
2098 my $record = C4::Biblio::UpsertMarcSubfield($MARC::Record, $fieldTag, $subfieldCode, $subfieldContent);
2102 sub UpsertMarcSubfield {
2103 my ($record, $tag, $code, $content) = @_;
2104 my $f = $record->field($tag);
2107 $f->update( $code => $content );
2110 my $f = MARC::Field->new( $tag, '', '', $code => $content);
2111 $record->insert_fields_ordered( $f );
2115 =head2 UpsertMarcControlField
2117 my $record = C4::Biblio::UpsertMarcControlField($MARC::Record, $fieldTag, $content);
2121 sub UpsertMarcControlField {
2122 my ($record, $tag, $content) = @_;
2123 die "UpsertMarcControlField() \$tag '$tag' is not a control field\n" unless 0+$tag < 10;
2124 my $f = $record->field($tag);
2127 $f->update( $content );
2130 my $f = MARC::Field->new($tag, $content);
2131 $record->insert_fields_ordered( $f );
2135 =head2 GetFrameworkCode
2137 $frameworkcode = GetFrameworkCode( $biblionumber )
2141 sub GetFrameworkCode {
2142 my ($biblionumber) = @_;
2143 my $dbh = C4::Context->dbh;
2144 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
2145 $sth->execute($biblionumber);
2146 my ($frameworkcode) = $sth->fetchrow;
2147 return $frameworkcode;
2150 =head2 TransformKohaToMarc
2152 $record = TransformKohaToMarc( $hash )
2154 This function builds partial MARC::Record from a hash
2155 Hash entries can be from biblio or biblioitems.
2157 This function is called in acquisition module, to create a basic catalogue
2158 entry from user entry
2163 sub TransformKohaToMarc {
2165 my $record = MARC::Record->new();
2166 SetMarcUnicodeFlag( $record, C4::Context->preference("marcflavour") );
2167 # FIXME Do not we want to get the marc subfield structure for the biblio framework?
2168 my $mss = GetMarcSubfieldStructure();
2170 while ( my ($kohafield, $value) = each %$hash ) {
2171 next unless exists $mss->{$kohafield};
2172 next unless $mss->{$kohafield};
2173 my $tagfield = $mss->{$kohafield}{tagfield} . '';
2174 my $tagsubfield = $mss->{$kohafield}{tagsubfield};
2175 foreach my $value ( split(/\s?\|\s?/, $value, -1) ) {
2176 next if $value eq '';
2177 $tag_hr->{$tagfield} //= [];
2178 push @{$tag_hr->{$tagfield}}, [($tagsubfield, $value)];
2181 foreach my $tag (sort keys %$tag_hr) {
2182 my @sfl = @{$tag_hr->{$tag}};
2183 @sfl = sort { $a->[0] cmp $b->[0]; } @sfl;
2184 @sfl = map { @{$_}; } @sfl;
2185 $record->insert_fields_ordered(
2186 MARC::Field->new($tag, " ", " ", @sfl)
2192 =head2 PrepHostMarcField
2194 $hostfield = PrepHostMarcField ( $hostbiblionumber,$hostitemnumber,$marcflavour )
2196 This function returns a host field populated with data from the host record, the field can then be added to an analytical record
2200 sub PrepHostMarcField {
2201 my ($hostbiblionumber,$hostitemnumber, $marcflavour) = @_;
2202 $marcflavour ||="MARC21";
2205 my $hostrecord = GetMarcBiblio($hostbiblionumber);
2206 my $item = C4::Items::GetItem($hostitemnumber);
2209 if ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) {
2213 if ($hostrecord->subfield('100','a')){
2214 $mainentry = $hostrecord->subfield('100','a');
2215 } elsif ($hostrecord->subfield('110','a')){
2216 $mainentry = $hostrecord->subfield('110','a');
2218 $mainentry = $hostrecord->subfield('111','a');
2221 # qualification info
2223 if (my $field260 = $hostrecord->field('260')){
2224 $qualinfo = $field260->as_string( 'abc' );
2229 my $ed = $hostrecord->subfield('250','a');
2230 my $barcode = $item->{'barcode'};
2231 my $title = $hostrecord->subfield('245','a');
2233 # record control number, 001 with 003 and prefix
2235 if ($hostrecord->field('001')){
2236 $recctrlno = $hostrecord->field('001')->data();
2237 if ($hostrecord->field('003')){
2238 $recctrlno = '('.$hostrecord->field('003')->data().')'.$recctrlno;
2243 my $issn = $hostrecord->subfield('022','a');
2244 my $isbn = $hostrecord->subfield('020','a');
2247 $hostmarcfield = MARC::Field->new(
2249 '0' => $hostbiblionumber,
2250 '9' => $hostitemnumber,
2260 } elsif ($marcflavour eq "UNIMARC") {
2261 $hostmarcfield = MARC::Field->new(
2263 '0' => $hostbiblionumber,
2264 't' => $hostrecord->subfield('200','a'),
2265 '9' => $hostitemnumber
2269 return $hostmarcfield;
2272 =head2 TransformHtmlToXml
2274 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator,
2275 $ind_tag, $auth_type )
2277 $auth_type contains :
2281 =item - nothing : rebuild a biblio. In UNIMARC the encoding is in 100$a pos 26/27
2283 =item - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
2285 =item - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
2291 sub TransformHtmlToXml {
2292 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
2293 # NOTE: The parameter $ind_tag is NOT USED -- BZ 11247
2295 my $xml = MARC::File::XML::header('UTF-8');
2296 $xml .= "<record>\n";
2297 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
2298 MARC::File::XML->default_record_format($auth_type);
2300 # in UNIMARC, field 100 contains the encoding
2301 # check that there is one, otherwise the
2302 # MARC::Record->new_from_xml will fail (and Koha will die)
2303 my $unimarc_and_100_exist = 0;
2304 $unimarc_and_100_exist = 1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
2309 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
2311 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a" ) {
2313 # if we have a 100 field and it's values are not correct, skip them.
2314 # if we don't have any valid 100 field, we will create a default one at the end
2315 my $enc = substr( @$values[$i], 26, 2 );
2316 if ( $enc eq '01' or $enc eq '50' or $enc eq '03' ) {
2317 $unimarc_and_100_exist = 1;
2322 @$values[$i] =~ s/&/&/g;
2323 @$values[$i] =~ s/</</g;
2324 @$values[$i] =~ s/>/>/g;
2325 @$values[$i] =~ s/"/"/g;
2326 @$values[$i] =~ s/'/'/g;
2328 if ( ( @$tags[$i] ne $prevtag ) ) {
2329 $j++ unless ( @$tags[$i] eq "" );
2330 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
2331 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
2332 my $ind1 = _default_ind_to_space($indicator1);
2334 if ( @$indicator[$j] ) {
2335 $ind2 = _default_ind_to_space($indicator2);
2337 warn "Indicator in @$tags[$i] is empty";
2341 $xml .= "</datafield>\n";
2342 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2343 && ( @$values[$i] ne "" ) ) {
2344 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2345 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2351 if ( @$values[$i] ne "" ) {
2354 if ( @$tags[$i] eq "000" ) {
2355 $xml .= "<leader>@$values[$i]</leader>\n";
2358 # rest of the fixed fields
2359 } elsif ( @$tags[$i] < 10 ) {
2360 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2363 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2364 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2369 } else { # @$tags[$i] eq $prevtag
2370 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
2371 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
2372 my $ind1 = _default_ind_to_space($indicator1);
2374 if ( @$indicator[$j] ) {
2375 $ind2 = _default_ind_to_space($indicator2);
2377 warn "Indicator in @$tags[$i] is empty";
2380 if ( @$values[$i] eq "" ) {
2383 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2386 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2389 $prevtag = @$tags[$i];
2391 $xml .= "</datafield>\n" if $xml =~ m/<datafield/;
2392 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist ) {
2394 # warn "SETTING 100 for $auth_type";
2395 my $string = strftime( "%Y%m%d", localtime(time) );
2397 # set 50 to position 26 is biblios, 13 if authorities
2399 $pos = 13 if $auth_type eq 'UNIMARCAUTH';
2400 $string = sprintf( "%-*s", 35, $string );
2401 substr( $string, $pos, 6, "50" );
2402 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2403 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2404 $xml .= "</datafield>\n";
2406 $xml .= "</record>\n";
2407 $xml .= MARC::File::XML::footer();
2411 =head2 _default_ind_to_space
2413 Passed what should be an indicator returns a space
2414 if its undefined or zero length
2418 sub _default_ind_to_space {
2420 if ( !defined $s || $s eq q{} ) {
2426 =head2 TransformHtmlToMarc
2428 L<$record> = TransformHtmlToMarc(L<$cgi>)
2429 L<$cgi> is the CGI object which containts the values for subfields
2431 'tag_010_indicator1_531951' ,
2432 'tag_010_indicator2_531951' ,
2433 'tag_010_code_a_531951_145735' ,
2434 'tag_010_subfield_a_531951_145735' ,
2435 'tag_200_indicator1_873510' ,
2436 'tag_200_indicator2_873510' ,
2437 'tag_200_code_a_873510_673465' ,
2438 'tag_200_subfield_a_873510_673465' ,
2439 'tag_200_code_b_873510_704318' ,
2440 'tag_200_subfield_b_873510_704318' ,
2441 'tag_200_code_e_873510_280822' ,
2442 'tag_200_subfield_e_873510_280822' ,
2443 'tag_200_code_f_873510_110730' ,
2444 'tag_200_subfield_f_873510_110730' ,
2446 L<$record> is the MARC::Record object.
2450 sub TransformHtmlToMarc {
2451 my ($cgi, $isbiblio) = @_;
2453 my @params = $cgi->multi_param();
2455 # explicitly turn on the UTF-8 flag for all
2456 # 'tag_' parameters to avoid incorrect character
2457 # conversion later on
2458 my $cgi_params = $cgi->Vars;
2459 foreach my $param_name ( keys %$cgi_params ) {
2460 if ( $param_name =~ /^tag_/ ) {
2461 my $param_value = $cgi_params->{$param_name};
2462 unless ( Encode::is_utf8( $param_value ) ) {
2463 $cgi_params->{$param_name} = Encode::decode('UTF-8', $param_value );
2468 # creating a new record
2469 my $record = MARC::Record->new();
2471 my ($biblionumbertagfield, $biblionumbertagsubfield) = (-1, -1);
2472 ($biblionumbertagfield, $biblionumbertagsubfield) =
2473 &GetMarcFromKohaField( "biblio.biblionumber", '' ) if $isbiblio;
2474 #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!
2475 for (my $i = 0; $params[$i]; $i++ ) { # browse all CGI params
2476 my $param = $params[$i];
2479 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2480 if ( $param eq 'biblionumber' ) {
2481 if ( $biblionumbertagfield < 10 ) {
2482 $newfield = MARC::Field->new( $biblionumbertagfield, scalar $cgi->param($param), );
2484 $newfield = MARC::Field->new( $biblionumbertagfield, '', '', "$biblionumbertagsubfield" => scalar $cgi->param($param), );
2486 push @fields, $newfield if ($newfield);
2487 } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..."
2490 my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) );
2491 my $ind2 = _default_ind_to_space( substr( $cgi->param( $params[ $i + 1 ] ), 0, 1 ) );
2495 if ( $tag < 10 ) { # no code for theses fields
2496 # in MARC editor, 000 contains the leader.
2497 next if $tag == $biblionumbertagfield;
2498 my $fval= $cgi->param($params[$j+1]);
2499 if ( $tag eq '000' ) {
2500 # Force a fake leader even if not provided to avoid crashing
2501 # during decoding MARC record containing UTF-8 characters
2503 length( $fval ) == 24
2508 # between 001 and 009 (included)
2509 } elsif ( $fval ne '' ) {
2510 $newfield = MARC::Field->new( $tag, $fval, );
2513 # > 009, deal with subfields
2515 # browse subfields for this tag (reason for _code_ match)
2516 while(defined $params[$j] && $params[$j] =~ /_code_/) {
2517 last unless defined $params[$j+1];
2519 if $tag == $biblionumbertagfield and
2520 $cgi->param($params[$j]) eq $biblionumbertagsubfield;
2521 #if next param ne subfield, then it was probably empty
2522 #try next param by incrementing j
2523 if($params[$j+1]!~/_subfield_/) {$j++; next; }
2524 my $fkey= $cgi->param($params[$j]);
2525 my $fval= $cgi->param($params[$j+1]);
2526 #check if subfield value not empty and field exists
2527 if($fval ne '' && $newfield) {
2528 $newfield->add_subfields( $fkey => $fval);
2530 elsif($fval ne '') {
2531 $newfield = MARC::Field->new( $tag, $ind1, $ind2, $fkey => $fval );
2535 $i= $j-1; #update i for outer loop accordingly
2537 push @fields, $newfield if ($newfield);
2541 $record->append_fields(@fields);
2545 =head2 TransformMarcToKoha
2547 $result = TransformMarcToKoha( $record, $frameworkcode )
2549 Extract data from a MARC bib record into a hashref representing
2550 Koha biblio, biblioitems, and items fields.
2552 If passed an undefined record will log the error and return an empty
2557 sub TransformMarcToKoha {
2558 my ( $record, $frameworkcode, $limit_table ) = @_;
2561 if (!defined $record) {
2562 carp('TransformMarcToKoha called with undefined record');
2565 $limit_table = $limit_table || 0;
2566 $frameworkcode = '' unless defined $frameworkcode;
2568 my $inverted_field_map = _get_inverted_marc_field_map($frameworkcode);
2571 if ( defined $limit_table && $limit_table eq 'items' ) {
2572 $tables{'items'} = 1;
2574 $tables{'items'} = 1;
2575 $tables{'biblio'} = 1;
2576 $tables{'biblioitems'} = 1;
2579 # traverse through record
2580 MARCFIELD: foreach my $field ( $record->fields() ) {
2581 my $tag = $field->tag();
2582 next MARCFIELD unless exists $inverted_field_map->{$tag};
2583 if ( $field->is_control_field() ) {
2584 my $kohafields = $inverted_field_map->{$tag}->{list};
2585 ENTRY: foreach my $entry ( @{$kohafields} ) {
2586 my ( $subfield, $table, $column ) = @{$entry};
2587 next ENTRY unless exists $tables{$table};
2588 my $key = _disambiguate( $table, $column );
2589 if ( $result->{$key} ) {
2590 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $field->data() eq "" ) ) {
2591 $result->{$key} .= " | " . $field->data();
2594 $result->{$key} = $field->data();
2599 # deal with subfields
2600 MARCSUBFIELD: foreach my $sf ( $field->subfields() ) {
2601 my $code = $sf->[0];
2602 next MARCSUBFIELD unless exists $inverted_field_map->{$tag}->{sfs}->{$code};
2603 my $value = $sf->[1];
2604 SFENTRY: foreach my $entry ( @{ $inverted_field_map->{$tag}->{sfs}->{$code} } ) {
2605 my ( $table, $column ) = @{$entry};
2606 next SFENTRY unless exists $tables{$table};
2607 my $key = _disambiguate( $table, $column );
2608 if ( $result->{$key} ) {
2609 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $value eq "" ) ) {
2610 $result->{$key} .= " | " . $value;
2613 $result->{$key} = $value;
2620 # modify copyrightdate to keep only the 1st year found
2621 if ( exists $result->{'copyrightdate'} ) {
2622 my $temp = $result->{'copyrightdate'};
2623 $temp =~ m/c(\d\d\d\d)/;
2624 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2625 $result->{'copyrightdate'} = $1;
2626 } else { # if no cYYYY, get the 1st date.
2627 $temp =~ m/(\d\d\d\d)/;
2628 $result->{'copyrightdate'} = $1;
2632 # modify publicationyear to keep only the 1st year found
2633 if ( exists $result->{'publicationyear'} ) {
2634 my $temp = $result->{'publicationyear'};
2635 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2636 $result->{'publicationyear'} = $1;
2637 } else { # if no cYYYY, get the 1st date.
2638 $temp =~ m/(\d\d\d\d)/;
2639 $result->{'publicationyear'} = $1;
2646 sub _get_inverted_marc_field_map {
2647 my ( $frameworkcode ) = @_;
2649 my $mss = GetMarcSubfieldStructure( $frameworkcode );
2651 foreach my $kohafield ( keys %{ $mss } ) {
2652 next unless exists $mss->{$kohafield}; # not all columns are mapped to MARC tag & subfield
2653 my $tag = $mss->{$kohafield}{tagfield};
2654 my $subfield = $mss->{$kohafield}{tagsubfield};
2655 my ( $table, $column ) = split /[.]/, $kohafield, 2;
2656 push @{ $field_map->{$tag}->{list} }, [ $subfield, $table, $column ];
2657 push @{ $field_map->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2662 =head2 _disambiguate
2664 $newkey = _disambiguate($table, $field);
2666 This is a temporary hack to distinguish between the
2667 following sets of columns when using TransformMarcToKoha.
2669 items.cn_source & biblioitems.cn_source
2670 items.cn_sort & biblioitems.cn_sort
2672 Columns that are currently NOT distinguished (FIXME
2673 due to lack of time to fully test) are:
2675 biblio.notes and biblioitems.notes
2680 FIXME - this is necessary because prefixing each column
2681 name with the table name would require changing lots
2682 of code and templates, and exposing more of the DB
2683 structure than is good to the UI templates, particularly
2684 since biblio and bibloitems may well merge in a future
2685 version. In the future, it would also be good to
2686 separate DB access and UI presentation field names
2691 sub CountItemsIssued {
2692 my ($biblionumber) = @_;
2693 my $dbh = C4::Context->dbh;
2694 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2695 $sth->execute($biblionumber);
2696 my $row = $sth->fetchrow_hashref();
2697 return $row->{'issuedCount'};
2701 my ( $table, $column ) = @_;
2702 if ( $column eq "cn_sort" or $column eq "cn_source" ) {
2703 return $table . '.' . $column;
2710 =head2 get_koha_field_from_marc
2712 $result->{_disambiguate($table, $field)} =
2713 get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2715 Internal function to map data from the MARC record to a specific non-MARC field.
2716 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2720 sub get_koha_field_from_marc {
2721 my ( $koha_table, $koha_column, $record, $frameworkcode ) = @_;
2722 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table . '.' . $koha_column, $frameworkcode );
2724 foreach my $field ( $record->field($tagfield) ) {
2725 if ( $field->tag() < 10 ) {
2727 $kohafield .= " | " . $field->data();
2729 $kohafield = $field->data();
2732 if ( $field->subfields ) {
2733 my @subfields = $field->subfields();
2734 foreach my $subfieldcount ( 0 .. $#subfields ) {
2735 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2737 $kohafield .= " | " . $subfields[$subfieldcount][1];
2739 $kohafield = $subfields[$subfieldcount][1];
2749 =head2 TransformMarcToKohaOneField
2751 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2755 sub TransformMarcToKohaOneField {
2757 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2758 # only the 1st will be retrieved...
2759 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2761 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $kohatable . "." . $kohafield, $frameworkcode );
2762 foreach my $field ( $record->field($tagfield) ) {
2763 if ( $field->tag() < 10 ) {
2764 if ( $result->{$kohafield} ) {
2765 $result->{$kohafield} .= " | " . $field->data();
2767 $result->{$kohafield} = $field->data();
2770 if ( $field->subfields ) {
2771 my @subfields = $field->subfields();
2772 foreach my $subfieldcount ( 0 .. $#subfields ) {
2773 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2774 if ( $result->{$kohafield} ) {
2775 $result->{$kohafield} .= " | " . $subfields[$subfieldcount][1];
2777 $result->{$kohafield} = $subfields[$subfieldcount][1];
2791 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2793 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2794 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2795 # =head2 ModZebrafiles
2797 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2801 # sub ModZebrafiles {
2803 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2807 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2808 # unless ( opendir( DIR, "$zebradir" ) ) {
2809 # warn "$zebradir not found";
2813 # my $filename = $zebradir . $biblionumber;
2816 # open( OUTPUT, ">", $filename . ".xml" );
2817 # print OUTPUT $record;
2824 ModZebra( $biblionumber, $op, $server, $record );
2826 $biblionumber is the biblionumber we want to index
2828 $op is specialUpdate or recordDelete, and is used to know what we want to do
2830 $server is the server that we want to update
2832 $record is the update MARC record if it's available. If it's not supplied
2833 and is needed, it'll be loaded from the database.
2838 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2839 my ( $biblionumber, $op, $server, $record ) = @_;
2840 $debug && warn "ModZebra: update requested for: $biblionumber $op $server\n";
2841 if ( C4::Context->preference('SearchEngine') eq 'Elasticsearch' ) {
2843 # TODO abstract to a standard API that'll work for whatever
2844 require Koha::SearchEngine::Elasticsearch::Indexer;
2845 my $indexer = Koha::SearchEngine::Elasticsearch::Indexer->new(
2847 index => $server eq 'biblioserver'
2848 ? $Koha::SearchEngine::BIBLIOS_INDEX
2849 : $Koha::SearchEngine::AUTHORITIES_INDEX
2852 if ( $op eq 'specialUpdate' ) {
2854 $record = GetMarcBiblio($biblionumber, 1);
2856 my $records = [$record];
2857 $indexer->update_index_background( [$biblionumber], [$record] );
2859 elsif ( $op eq 'recordDelete' ) {
2860 $indexer->delete_index_background( [$biblionumber] );
2863 croak "ModZebra called with unknown operation: $op";
2867 my $dbh = C4::Context->dbh;
2869 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2871 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2872 # the table is emptied by rebuild_zebra.pl script (using the -z switch)
2873 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2875 AND biblio_auth_number = ?
2878 my $check_sth = $dbh->prepare_cached($check_sql);
2879 $check_sth->execute( $server, $biblionumber, $op );
2880 my ($count) = $check_sth->fetchrow_array;
2881 $check_sth->finish();
2882 if ( $count == 0 ) {
2883 my $sth = $dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2884 $sth->execute( $biblionumber, $server, $op );
2890 =head2 EmbedItemsInMarcBiblio
2892 EmbedItemsInMarcBiblio($marc, $biblionumber, $itemnumbers, $opac);
2894 Given a MARC::Record object containing a bib record,
2895 modify it to include the items attached to it as 9XX
2896 per the bib's MARC framework.
2897 if $itemnumbers is defined, only specified itemnumbers are embedded.
2899 If $opac is true, then opac-relevant suppressions are included.
2903 sub EmbedItemsInMarcBiblio {
2904 my ($marc, $biblionumber, $itemnumbers, $opac) = @_;
2906 carp 'EmbedItemsInMarcBiblio: No MARC record passed';
2910 $itemnumbers = [] unless defined $itemnumbers;
2912 my $frameworkcode = GetFrameworkCode($biblionumber);
2913 _strip_item_fields($marc, $frameworkcode);
2915 # ... and embed the current items
2916 my $dbh = C4::Context->dbh;
2917 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
2918 $sth->execute($biblionumber);
2920 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2922 my $opachiddenitems = $opac
2923 && ( C4::Context->preference('OpacHiddenItems') !~ /^\s*$/ );
2925 while ( my ($itemnumber) = $sth->fetchrow_array ) {
2926 next if @$itemnumbers and not grep { $_ == $itemnumber } @$itemnumbers;
2927 my $i = $opachiddenitems ? C4::Items::GetItem($itemnumber) : undef;
2928 push @items, { itemnumber => $itemnumber, item => $i };
2932 ? C4::Items::GetHiddenItemnumbers( map { $_->{item} } @items )
2934 # Convert to a hash for quick searching
2935 my %hiddenitems = map { $_ => 1 } @hiddenitems;
2936 foreach my $itemnumber ( map { $_->{itemnumber} } @items ) {
2937 next if $hiddenitems{$itemnumber};
2938 my $item_marc = C4::Items::GetMarcItem( $biblionumber, $itemnumber );
2939 push @item_fields, $item_marc->field($itemtag);
2941 $marc->append_fields(@item_fields);
2944 =head1 INTERNAL FUNCTIONS
2946 =head2 _koha_marc_update_bib_ids
2949 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2951 Internal function to add or update biblionumber and biblioitemnumber to
2956 sub _koha_marc_update_bib_ids {
2957 my ( $record, $frameworkcode, $biblionumber, $biblioitemnumber ) = @_;
2959 my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
2960 die qq{No biblionumber tag for framework "$frameworkcode"} unless $biblio_tag;
2961 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
2962 die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag;
2964 if ( $biblio_tag < 10 ) {
2965 C4::Biblio::UpsertMarcControlField( $record, $biblio_tag, $biblionumber );
2967 C4::Biblio::UpsertMarcSubfield($record, $biblio_tag, $biblio_subfield, $biblionumber);
2969 if ( $biblioitem_tag < 10 ) {
2970 C4::Biblio::UpsertMarcControlField( $record, $biblioitem_tag, $biblioitemnumber );
2972 C4::Biblio::UpsertMarcSubfield($record, $biblioitem_tag, $biblioitem_subfield, $biblioitemnumber);
2976 =head2 _koha_marc_update_biblioitem_cn_sort
2978 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2980 Given a MARC bib record and the biblioitem hash, update the
2981 subfield that contains a copy of the value of biblioitems.cn_sort.
2985 sub _koha_marc_update_biblioitem_cn_sort {
2987 my $biblioitem = shift;
2988 my $frameworkcode = shift;
2990 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.cn_sort", $frameworkcode );
2991 return unless $biblioitem_tag;
2993 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2995 if ( my $field = $marc->field($biblioitem_tag) ) {
2996 $field->delete_subfield( code => $biblioitem_subfield );
2997 if ( $cn_sort ne '' ) {
2998 $field->add_subfields( $biblioitem_subfield => $cn_sort );
3002 # if we get here, no biblioitem tag is present in the MARC record, so
3003 # we'll create it if $cn_sort is not empty -- this would be
3004 # an odd combination of events, however
3006 $marc->insert_grouped_field( MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) );
3011 =head2 _koha_add_biblio
3013 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3015 Internal function to add a biblio ($biblio is a hash with the values)
3019 sub _koha_add_biblio {
3020 my ( $dbh, $biblio, $frameworkcode ) = @_;
3024 # set the series flag
3025 unless (defined $biblio->{'serial'}){
3026 $biblio->{'serial'} = 0;
3027 if ( $biblio->{'seriestitle'} ) { $biblio->{'serial'} = 1 }
3030 my $query = "INSERT INTO biblio
3031 SET frameworkcode = ?,
3042 my $sth = $dbh->prepare($query);
3044 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
3045 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}
3048 my $biblionumber = $dbh->{'mysql_insertid'};
3049 if ( $dbh->errstr ) {
3050 $error .= "ERROR in _koha_add_biblio $query" . $dbh->errstr;
3056 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3057 return ( $biblionumber, $error );
3060 =head2 _koha_modify_biblio
3062 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3064 Internal function for updating the biblio table
3068 sub _koha_modify_biblio {
3069 my ( $dbh, $biblio, $frameworkcode ) = @_;
3074 SET frameworkcode = ?,
3083 WHERE biblionumber = ?
3086 my $sth = $dbh->prepare($query);
3089 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
3090 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}, $biblio->{'biblionumber'}
3091 ) if $biblio->{'biblionumber'};
3093 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3094 $error .= "ERROR in _koha_modify_biblio $query" . $dbh->errstr;
3097 return ( $biblio->{'biblionumber'}, $error );
3100 =head2 _koha_modify_biblioitem_nonmarc
3102 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3106 sub _koha_modify_biblioitem_nonmarc {
3107 my ( $dbh, $biblioitem ) = @_;
3110 # re-calculate the cn_sort, it may have changed
3111 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3113 my $query = "UPDATE biblioitems
3114 SET biblionumber = ?,
3120 publicationyear = ?,
3124 collectiontitle = ?,
3126 collectionvolume= ?,
3127 editionstatement= ?,
3128 editionresponsibility = ?,
3144 where biblioitemnumber = ?
3146 my $sth = $dbh->prepare($query);
3148 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3149 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3150 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3151 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3152 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3153 $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'},
3154 $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'},
3155 $biblioitem->{'ean'}, $biblioitem->{'agerestriction'}, $biblioitem->{'biblioitemnumber'}
3157 if ( $dbh->errstr ) {
3158 $error .= "ERROR in _koha_modify_biblioitem_nonmarc $query" . $dbh->errstr;
3161 return ( $biblioitem->{'biblioitemnumber'}, $error );
3164 =head2 _koha_add_biblioitem
3166 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3168 Internal function to add a biblioitem
3172 sub _koha_add_biblioitem {
3173 my ( $dbh, $biblioitem ) = @_;
3176 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3177 my $query = "INSERT INTO biblioitems SET
3184 publicationyear = ?,
3188 collectiontitle = ?,
3190 collectionvolume= ?,
3191 editionstatement= ?,
3192 editionresponsibility = ?,
3209 my $sth = $dbh->prepare($query);
3211 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3212 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3213 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3214 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3215 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3216 $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'},
3217 $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort,
3218 $biblioitem->{'totalissues'}, $biblioitem->{'ean'}, $biblioitem->{'agerestriction'}
3220 my $bibitemnum = $dbh->{'mysql_insertid'};
3222 if ( $dbh->errstr ) {
3223 $error .= "ERROR in _koha_add_biblioitem $query" . $dbh->errstr;
3227 return ( $bibitemnum, $error );
3230 =head2 _koha_delete_biblio
3232 $error = _koha_delete_biblio($dbh,$biblionumber);
3234 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3236 C<$dbh> - the database handle
3238 C<$biblionumber> - the biblionumber of the biblio to be deleted
3242 # FIXME: add error handling
3244 sub _koha_delete_biblio {
3245 my ( $dbh, $biblionumber ) = @_;
3247 # get all the data for this biblio
3248 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3249 $sth->execute($biblionumber);
3251 # FIXME There is a transaction in _koha_delete_biblio_metadata
3252 # But actually all the following should be done inside a single transaction
3253 if ( my $data = $sth->fetchrow_hashref ) {
3255 # save the record in deletedbiblio
3256 # find the fields to save
3257 my $query = "INSERT INTO deletedbiblio SET ";
3259 foreach my $temp ( keys %$data ) {
3260 $query .= "$temp = ?,";
3261 push( @bind, $data->{$temp} );
3264 # replace the last , by ",?)"
3266 my $bkup_sth = $dbh->prepare($query);
3267 $bkup_sth->execute(@bind);
3270 _koha_delete_biblio_metadata( $biblionumber );
3273 my $sth2 = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3274 $sth2->execute($biblionumber);
3275 # update the timestamp (Bugzilla 7146)
3276 $sth2= $dbh->prepare("UPDATE deletedbiblio SET timestamp=NOW() WHERE biblionumber=?");
3277 $sth2->execute($biblionumber);
3284 =head2 _koha_delete_biblioitems
3286 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3288 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3290 C<$dbh> - the database handle
3291 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3295 # FIXME: add error handling
3297 sub _koha_delete_biblioitems {
3298 my ( $dbh, $biblioitemnumber ) = @_;
3300 # get all the data for this biblioitem
3301 my $sth = $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3302 $sth->execute($biblioitemnumber);
3304 if ( my $data = $sth->fetchrow_hashref ) {
3306 # save the record in deletedbiblioitems
3307 # find the fields to save
3308 my $query = "INSERT INTO deletedbiblioitems SET ";
3310 foreach my $temp ( keys %$data ) {
3311 $query .= "$temp = ?,";
3312 push( @bind, $data->{$temp} );
3315 # replace the last , by ",?)"
3317 my $bkup_sth = $dbh->prepare($query);
3318 $bkup_sth->execute(@bind);
3321 # delete the biblioitem
3322 my $sth2 = $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3323 $sth2->execute($biblioitemnumber);
3324 # update the timestamp (Bugzilla 7146)
3325 $sth2= $dbh->prepare("UPDATE deletedbiblioitems SET timestamp=NOW() WHERE biblioitemnumber=?");
3326 $sth2->execute($biblioitemnumber);
3333 =head2 _koha_delete_biblio_metadata
3335 $error = _koha_delete_biblio_metadata($biblionumber);
3337 C<$biblionumber> - the biblionumber of the biblio metadata to be deleted
3341 sub _koha_delete_biblio_metadata {
3342 my ($biblionumber) = @_;
3344 my $dbh = C4::Context->dbh;
3345 my $schema = Koha::Database->new->schema;
3349 INSERT INTO deletedbiblio_metadata (biblionumber, format, marcflavour, metadata)
3350 SELECT biblionumber, format, marcflavour, metadata FROM biblio_metadata WHERE biblionumber=?
3351 |, undef, $biblionumber );
3352 $dbh->do( q|DELETE FROM biblio_metadata WHERE biblionumber=?|,
3353 undef, $biblionumber );
3358 =head1 UNEXPORTED FUNCTIONS
3360 =head2 ModBiblioMarc
3362 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3364 Add MARC XML data for a biblio to koha
3366 Function exported, but should NOT be used, unless you really know what you're doing
3371 # pass the MARC::Record to this function, and it will create the records in
3373 my ( $record, $biblionumber, $frameworkcode ) = @_;
3375 carp 'ModBiblioMarc passed an undefined record';
3379 # Clone record as it gets modified
3380 $record = $record->clone();
3381 my $dbh = C4::Context->dbh;
3382 my @fields = $record->fields();
3383 if ( !$frameworkcode ) {
3384 $frameworkcode = "";
3386 my $sth = $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3387 $sth->execute( $frameworkcode, $biblionumber );
3389 my $encoding = C4::Context->preference("marcflavour");
3391 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3392 if ( $encoding eq "UNIMARC" ) {
3393 my $defaultlanguage = C4::Context->preference("UNIMARCField100Language");
3394 $defaultlanguage = "fre" if (!$defaultlanguage || length($defaultlanguage) != 3);
3395 my $string = $record->subfield( 100, "a" );
3396 if ( ($string) && ( length( $record->subfield( 100, "a" ) ) == 36 ) ) {
3397 my $f100 = $record->field(100);
3398 $record->delete_field($f100);
3400 $string = POSIX::strftime( "%Y%m%d", localtime );
3402 $string = sprintf( "%-*s", 35, $string );
3403 substr ( $string, 22, 3, $defaultlanguage);
3405 substr( $string, 25, 3, "y50" );
3406 unless ( $record->subfield( 100, "a" ) ) {
3407 $record->insert_fields_ordered( MARC::Field->new( 100, "", "", "a" => $string ) );
3411 #enhancement 5374: update transaction date (005) for marc21/unimarc
3412 if($encoding =~ /MARC21|UNIMARC/) {
3413 my @a= (localtime) [5,4,3,2,1,0]; $a[0]+=1900; $a[1]++;
3414 # YY MM DD HH MM SS (update year and month)
3415 my $f005= $record->field('005');
3416 $f005->update(sprintf("%4d%02d%02d%02d%02d%04.1f",@a)) if $f005;
3420 biblionumber => $biblionumber,
3421 format => 'marcxml',
3422 marcflavour => C4::Context->preference('marcflavour'),
3424 # FIXME To replace with ->find_or_create?
3425 if ( my $m_rs = Koha::Biblio::Metadatas->find($metadata) ) {
3426 $m_rs->metadata( $record->as_xml_record($encoding) );
3429 my $m_rs = Koha::Biblio::Metadata->new($metadata);
3430 $m_rs->metadata( $record->as_xml_record($encoding) );
3433 ModZebra( $biblionumber, "specialUpdate", "biblioserver", $record );
3434 return $biblionumber;
3437 =head2 CountBiblioInOrders
3439 $count = &CountBiblioInOrders( $biblionumber);
3441 This function return count of biblios in orders with $biblionumber
3445 sub CountBiblioInOrders {
3446 my ($biblionumber) = @_;
3447 my $dbh = C4::Context->dbh;
3448 my $query = "SELECT count(*)
3450 WHERE biblionumber=? AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')";
3451 my $sth = $dbh->prepare($query);
3452 $sth->execute($biblionumber);
3453 my $count = $sth->fetchrow;
3457 =head2 GetSubscriptionsId
3459 $subscriptions = &GetSubscriptionsId($biblionumber);
3461 This function return an array of subscriptionid with $biblionumber
3465 sub GetSubscriptionsId {
3466 my ($biblionumber) = @_;
3467 my $dbh = C4::Context->dbh;
3468 my $query = "SELECT subscriptionid
3470 WHERE biblionumber=?";
3471 my $sth = $dbh->prepare($query);
3472 $sth->execute($biblionumber);
3473 my @subscriptions = $sth->fetchrow_array;
3474 return (@subscriptions);
3477 =head2 prepare_host_field
3479 $marcfield = prepare_host_field( $hostbiblioitem, $marcflavour );
3480 Generate the host item entry for an analytic child entry
3484 sub prepare_host_field {
3485 my ( $hostbiblio, $marcflavour ) = @_;
3486 $marcflavour ||= C4::Context->preference('marcflavour');
3487 my $host = GetMarcBiblio($hostbiblio);
3488 # unfortunately as_string does not 'do the right thing'
3489 # if field returns undef
3493 if ( $marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC' ) {
3494 if ( $field = $host->field('100') || $host->field('110') || $host->field('11') ) {
3495 my $s = $field->as_string('ab');
3500 if ( $field = $host->field('245') ) {
3501 my $s = $field->as_string('a');
3506 if ( $field = $host->field('260') ) {
3507 my $s = $field->as_string('abc');
3512 if ( $field = $host->field('240') ) {
3513 my $s = $field->as_string();
3518 if ( $field = $host->field('022') ) {
3519 my $s = $field->as_string('a');
3524 if ( $field = $host->field('020') ) {
3525 my $s = $field->as_string('a');
3530 if ( $field = $host->field('001') ) {
3531 $sfd{w} = $field->data(),;
3533 $host_field = MARC::Field->new( 773, '0', ' ', %sfd );
3536 elsif ( $marcflavour eq 'UNIMARC' ) {
3538 if ( $field = $host->field('700') || $host->field('710') || $host->field('720') ) {
3539 my $s = $field->as_string('ab');
3545 if ( $field = $host->field('200') ) {
3546 my $s = $field->as_string('a');
3551 #place of publicaton
3552 if ( $field = $host->field('210') ) {
3553 my $s = $field->as_string('a');
3558 #date of publication
3559 if ( $field = $host->field('210') ) {
3560 my $s = $field->as_string('d');
3566 if ( $field = $host->field('205') ) {
3567 my $s = $field->as_string();
3573 if ( $field = $host->field('856') ) {
3574 my $s = $field->as_string('u');
3580 if ( $field = $host->field('011') ) {
3581 my $s = $field->as_string('a');
3587 if ( $field = $host->field('010') ) {
3588 my $s = $field->as_string('a');
3593 if ( $field = $host->field('001') ) {
3594 $sfd{0} = $field->data(),;
3596 $host_field = MARC::Field->new( 461, '0', ' ', %sfd );
3603 =head2 UpdateTotalIssues
3605 UpdateTotalIssues($biblionumber, $increase, [$value])
3607 Update the total issue count for a particular bib record.
3611 =item C<$biblionumber> is the biblionumber of the bib to update
3613 =item C<$increase> is the amount to increase (or decrease) the total issues count by
3615 =item C<$value> is the absolute value that total issues count should be set to. If provided, C<$increase> is ignored.
3621 sub UpdateTotalIssues {
3622 my ($biblionumber, $increase, $value) = @_;
3625 my $record = GetMarcBiblio($biblionumber);
3627 carp "UpdateTotalIssues could not get biblio record";
3630 my $data = GetBiblioData($biblionumber);
3632 carp "UpdateTotalIssues could not get datas of biblio";
3635 my ($totalissuestag, $totalissuessubfield) = GetMarcFromKohaField('biblioitems.totalissues', $data->{'frameworkcode'});
3636 unless ($totalissuestag) {
3637 return 1; # There is nothing to do
3640 if (defined $value) {
3641 $totalissues = $value;
3643 $totalissues = $data->{'totalissues'} + $increase;
3646 my $field = $record->field($totalissuestag);
3647 if (defined $field) {
3648 $field->update( $totalissuessubfield => $totalissues );
3650 $field = MARC::Field->new($totalissuestag, '0', '0',
3651 $totalissuessubfield => $totalissues);
3652 $record->insert_grouped_field($field);
3655 return ModBiblio($record, $biblionumber, $data->{'frameworkcode'});
3660 &RemoveAllNsb($record);
3662 Removes all nsb/nse chars from a record
3669 carp 'RemoveAllNsb called with undefined record';
3673 SetUTF8Flag($record);
3675 foreach my $field ($record->fields()) {
3676 if ($field->is_control_field()) {
3677 $field->update(nsb_clean($field->data()));
3679 my @subfields = $field->subfields();
3681 foreach my $subfield (@subfields) {
3682 push @new_subfields, $subfield->[0] => nsb_clean($subfield->[1]);
3684 if (scalar(@new_subfields) > 0) {
3687 $new_field = MARC::Field->new(
3689 $field->indicator(1),
3690 $field->indicator(2),
3695 warn "error in RemoveAllNsb : $@";
3697 $field->replace_with($new_field);
3713 Koha Development Team <http://koha-community.org/>
3715 Paul POULAIN paul.poulain@free.fr
3717 Joshua Ferraro jmf@liblime.com