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 under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 use MARC::File::USMARC;
30 use POSIX qw(strftime);
33 use C4::Dates qw/format_date/;
34 use C4::Log; # logaction
38 use vars qw($VERSION @ISA @EXPORT);
44 @ISA = qw( Exporter );
59 &GetBiblioItemByBiblioNumber
60 &GetBiblioFromItemNumber
61 &GetBiblionumberFromItemnumber
85 &GetAuthorisedValueDesc
105 # To delete something
110 # To link headings in a bib record
111 # to authority records.
113 &LinkBibHeadingsToAuthorities
117 # those functions are exported but should not be used
118 # they are usefull is few circumstances, so are exported.
119 # but don't use them unless you're a core developer ;-)
127 &TransformHtmlToMarc2
135 if (C4::Context->ismemcached) {
136 require Memoize::Memcached;
137 import Memoize::Memcached qw(memoize_memcached);
139 memoize_memcached( 'GetMarcStructure',
140 memcached => C4::Context->memcached);
146 C4::Biblio - cataloging management functions
150 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:
154 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
156 =item 2. as raw MARC in the Zebra index and storage engine
158 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
162 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
164 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.
168 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
170 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
174 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:
178 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
180 =item 2. _koha_* - low-level internal functions for managing the koha tables
182 =item 3. Marc management function : as the MARC record is stored in biblioitems.marc(xml), 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.
184 =item 4. Zebra functions used to update the Zebra index
186 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
190 The MARC record (in biblioitems.marcxml) 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 :
194 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
196 =item 2. add the biblionumber and biblioitemnumber into the MARC records
198 =item 3. save the marc record
202 When dealing with items, we must :
206 =item 1. save the item in items table, that gives us an itemnumber
208 =item 2. add the itemnumber to the item MARC field
210 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
212 When modifying a biblio or an item, the behaviour is quite similar.
216 =head1 EXPORTED FUNCTIONS
220 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
222 Exported function (core API) for adding a new biblio to koha.
224 The first argument is a C<MARC::Record> object containing the
225 bib to add, while the second argument is the desired MARC
228 This function also accepts a third, optional argument: a hashref
229 to additional options. The only defined option is C<defer_marc_save>,
230 which if present and mapped to a true value, causes C<AddBiblio>
231 to omit the call to save the MARC in C<bibilioitems.marc>
232 and C<biblioitems.marcxml> This option is provided B<only>
233 for the use of scripts such as C<bulkmarcimport.pl> that may need
234 to do some manipulation of the MARC record for item parsing before
235 saving it and which cannot afford the performance hit of saving
236 the MARC record twice. Consequently, do not use that option
237 unless you can guarantee that C<ModBiblioMarc> will be called.
243 my $frameworkcode = shift;
244 my $options = @_ ? shift : undef;
245 my $defer_marc_save = 0;
246 if ( defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'} ) {
247 $defer_marc_save = 1;
250 my ( $biblionumber, $biblioitemnumber, $error );
251 my $dbh = C4::Context->dbh;
253 # transform the data into koha-table style data
254 SetUTF8Flag($record);
255 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
256 ( $biblionumber, $error ) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
257 $olddata->{'biblionumber'} = $biblionumber;
258 ( $biblioitemnumber, $error ) = _koha_add_biblioitem( $dbh, $olddata );
260 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
262 # update MARC subfield that stores biblioitems.cn_sort
263 _koha_marc_update_biblioitem_cn_sort( $record, $olddata, $frameworkcode );
266 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
268 logaction( "CATALOGUING", "ADD", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
269 return ( $biblionumber, $biblioitemnumber );
274 ModBiblio( $record,$biblionumber,$frameworkcode);
276 Replace an existing bib record identified by C<$biblionumber>
277 with one supplied by the MARC::Record object C<$record>. The embedded
278 item, biblioitem, and biblionumber fields from the previous
279 version of the bib record replace any such fields of those tags that
280 are present in C<$record>. Consequently, ModBiblio() is not
281 to be used to try to modify item records.
283 C<$frameworkcode> specifies the MARC framework to use
284 when storing the modified bib record; among other things,
285 this controls how MARC fields get mapped to display columns
286 in the C<biblio> and C<biblioitems> tables, as well as
287 which fields are used to store embedded item, biblioitem,
288 and biblionumber data for indexing.
293 my ( $record, $biblionumber, $frameworkcode ) = @_;
294 croak "No record" unless $record;
296 if ( C4::Context->preference("CataloguingLog") ) {
297 my $newrecord = GetMarcBiblio($biblionumber);
298 logaction( "CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>" . $newrecord->as_formatted );
301 # Cleaning up invalid fields must be done early or SetUTF8Flag is liable to
302 # throw an exception which probably won't be handled.
303 foreach my $field ($record->fields()) {
304 if (! $field->is_control_field()) {
305 if (scalar($field->subfields()) == 0 || (scalar($field->subfields()) == 1 && $field->subfield('9'))) {
306 $record->delete_field($field);
311 SetUTF8Flag($record);
312 my $dbh = C4::Context->dbh;
314 $frameworkcode = "" if !$frameworkcode || $frameworkcode eq "Default"; # XXX
316 _strip_item_fields($record, $frameworkcode);
318 # update biblionumber and biblioitemnumber in MARC
319 # FIXME - this is assuming a 1 to 1 relationship between
320 # biblios and biblioitems
321 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
322 $sth->execute($biblionumber);
323 my ($biblioitemnumber) = $sth->fetchrow;
325 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
327 # load the koha-table data object
328 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
330 # update MARC subfield that stores biblioitems.cn_sort
331 _koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode );
333 # update the MARC record (that now contains biblio and items) with the new record data
334 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
336 # modify the other koha tables
337 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
338 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
342 =head2 _strip_item_fields
344 _strip_item_fields($record, $frameworkcode)
346 Utility routine to remove item tags from a
351 sub _strip_item_fields {
353 my $frameworkcode = shift;
354 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
355 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
357 # delete any item fields from incoming record to avoid
358 # duplication or incorrect data - use AddItem() or ModItem()
360 foreach my $field ( $record->field($itemtag) ) {
361 $record->delete_field($field);
365 =head2 ModBiblioframework
367 ModBiblioframework($biblionumber,$frameworkcode);
369 Exported function to modify a biblio framework
373 sub ModBiblioframework {
374 my ( $biblionumber, $frameworkcode ) = @_;
375 my $dbh = C4::Context->dbh;
376 my $sth = $dbh->prepare( "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?" );
377 $sth->execute( $frameworkcode, $biblionumber );
383 my $error = &DelBiblio($biblionumber);
385 Exported function (core API) for deleting a biblio in koha.
386 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
387 Also backs it up to deleted* tables
388 Checks to make sure there are not issues on any of the items
390 C<$error> : undef unless an error occurs
395 my ($biblionumber) = @_;
396 my $dbh = C4::Context->dbh;
397 my $error; # for error handling
399 # First make sure this biblio has no items attached
400 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
401 $sth->execute($biblionumber);
402 if ( my $itemnumber = $sth->fetchrow ) {
404 # Fix this to use a status the template can understand
405 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
408 return $error if $error;
410 # We delete attached subscriptions
412 my $subscriptions = C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
413 foreach my $subscription (@$subscriptions) {
414 C4::Serials::DelSubscription( $subscription->{subscriptionid} );
417 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
418 # for at least 2 reasons :
419 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
420 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
421 # 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)
423 if ( C4::Context->preference("NoZebra") ) {
425 # only NoZebra indexing needs to have
426 # the previous version of the record
427 $oldRecord = GetMarcBiblio($biblionumber);
429 ModZebra( $biblionumber, "recordDelete", "biblioserver", $oldRecord, undef );
431 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
432 $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
433 $sth->execute($biblionumber);
434 while ( my $biblioitemnumber = $sth->fetchrow ) {
436 # delete this biblioitem
437 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
438 return $error if $error;
441 # delete biblio from Koha tables and save in deletedbiblio
442 # must do this *after* _koha_delete_biblioitems, otherwise
443 # delete cascade will prevent deletedbiblioitems rows
444 # from being generated by _koha_delete_biblioitems
445 $error = _koha_delete_biblio( $dbh, $biblionumber );
447 logaction( "CATALOGUING", "DELETE", $biblionumber, "" ) if C4::Context->preference("CataloguingLog");
452 =head2 LinkBibHeadingsToAuthorities
454 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
456 Links bib headings to authority records by checking
457 each authority-controlled field in the C<MARC::Record>
458 object C<$marc>, looking for a matching authority record,
459 and setting the linking subfield $9 to the ID of that
462 If no matching authority exists, or if multiple
463 authorities match, no $9 will be added, and any
464 existing one inthe field will be deleted.
466 Returns the number of heading links changed in the
471 sub LinkBibHeadingsToAuthorities {
475 my $num_headings_changed = 0;
476 foreach my $field ( $bib->fields() ) {
477 my $heading = C4::Heading->new_from_bib_field($field);
478 next unless defined $heading;
481 my $current_link = $field->subfield('9');
483 # look for matching authorities
484 my $authorities = $heading->authorities();
486 # want only one exact match
487 if ( $#{$authorities} == 0 ) {
488 my $authority = MARC::Record->new_from_usmarc( $authorities->[0] );
489 my $authid = $authority->field('001')->data();
490 next if defined $current_link and $current_link eq $authid;
492 $field->delete_subfield( code => '9' ) if defined $current_link;
493 $field->add_subfields( '9', $authid );
494 $num_headings_changed++;
496 if ( defined $current_link ) {
497 $field->delete_subfield( code => '9' );
498 $num_headings_changed++;
503 return $num_headings_changed;
506 =head2 GetRecordValue
508 my $values = GetRecordValue($field, $record, $frameworkcode);
510 Get MARC fields from a keyword defined in fieldmapping table.
515 my ( $field, $record, $frameworkcode ) = @_;
516 my $dbh = C4::Context->dbh;
518 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
519 $sth->execute( $frameworkcode, $field );
523 while ( my $row = $sth->fetchrow_hashref ) {
524 foreach my $field ( $record->field( $row->{fieldcode} ) ) {
525 if ( ( $row->{subfieldcode} ne "" && $field->subfield( $row->{subfieldcode} ) ) ) {
526 foreach my $subfield ( $field->subfield( $row->{subfieldcode} ) ) {
527 push @result, { 'subfield' => $subfield };
530 } elsif ( $row->{subfieldcode} eq "" ) {
531 push @result, { 'subfield' => $field->as_string() };
539 =head2 SetFieldMapping
541 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
543 Set a Field to MARC mapping value, if it already exists we don't add a new one.
547 sub SetFieldMapping {
548 my ( $framework, $field, $fieldcode, $subfieldcode ) = @_;
549 my $dbh = C4::Context->dbh;
551 my $sth = $dbh->prepare('SELECT * FROM fieldmapping WHERE fieldcode = ? AND subfieldcode = ? AND frameworkcode = ? AND field = ?');
552 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
553 if ( not $sth->fetchrow_hashref ) {
555 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
557 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
561 =head2 DeleteFieldMapping
563 DeleteFieldMapping($id);
565 Delete a field mapping from an $id.
569 sub DeleteFieldMapping {
571 my $dbh = C4::Context->dbh;
573 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
577 =head2 GetFieldMapping
579 GetFieldMapping($frameworkcode);
581 Get all field mappings for a specified frameworkcode
585 sub GetFieldMapping {
586 my ($framework) = @_;
587 my $dbh = C4::Context->dbh;
589 my $sth = $dbh->prepare('SELECT * FROM fieldmapping where frameworkcode = ?');
590 $sth->execute($framework);
593 while ( my $row = $sth->fetchrow_hashref ) {
601 $data = &GetBiblioData($biblionumber);
603 Returns information about the book with the given biblionumber.
604 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
605 the C<biblio> and C<biblioitems> tables in the
608 In addition, C<$data-E<gt>{subject}> is the list of the book's
609 subjects, separated by C<" , "> (space, comma, space).
610 If there are multiple biblioitems with the given biblionumber, only
611 the first one is considered.
617 my $dbh = C4::Context->dbh;
619 # my $query = C4::Context->preference('item-level_itypes') ?
620 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
622 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
623 # WHERE biblio.biblionumber = ?
624 # AND biblioitems.biblionumber = biblio.biblionumber
627 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
629 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
630 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
631 WHERE biblio.biblionumber = ?
632 AND biblioitems.biblionumber = biblio.biblionumber ";
634 my $sth = $dbh->prepare($query);
635 $sth->execute($bibnum);
637 $data = $sth->fetchrow_hashref;
641 } # sub GetBiblioData
643 =head2 &GetBiblioItemData
645 $itemdata = &GetBiblioItemData($biblioitemnumber);
647 Looks up the biblioitem with the given biblioitemnumber. Returns a
648 reference-to-hash. The keys are the fields from the C<biblio>,
649 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
650 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
655 sub GetBiblioItemData {
656 my ($biblioitemnumber) = @_;
657 my $dbh = C4::Context->dbh;
658 my $query = "SELECT *,biblioitems.notes AS bnotes
659 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
660 unless ( C4::Context->preference('item-level_itypes') ) {
661 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
663 $query .= " WHERE biblioitemnumber = ? ";
664 my $sth = $dbh->prepare($query);
666 $sth->execute($biblioitemnumber);
667 $data = $sth->fetchrow_hashref;
670 } # sub &GetBiblioItemData
672 =head2 GetBiblioItemByBiblioNumber
674 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
678 sub GetBiblioItemByBiblioNumber {
679 my ($biblionumber) = @_;
680 my $dbh = C4::Context->dbh;
681 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
685 $sth->execute($biblionumber);
687 while ( my $data = $sth->fetchrow_hashref ) {
688 push @results, $data;
695 =head2 GetBiblionumberFromItemnumber
700 sub GetBiblionumberFromItemnumber {
701 my ($itemnumber) = @_;
702 my $dbh = C4::Context->dbh;
703 my $sth = $dbh->prepare("Select biblionumber FROM items WHERE itemnumber = ?");
705 $sth->execute($itemnumber);
706 my ($result) = $sth->fetchrow;
710 =head2 GetBiblioFromItemNumber
712 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
714 Looks up the item with the given itemnumber. if undef, try the barcode.
716 C<&itemnodata> returns a reference-to-hash whose keys are the fields
717 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
723 sub GetBiblioFromItemNumber {
724 my ( $itemnumber, $barcode ) = @_;
725 my $dbh = C4::Context->dbh;
728 $sth = $dbh->prepare(
730 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
731 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
732 WHERE items.itemnumber = ?"
734 $sth->execute($itemnumber);
736 $sth = $dbh->prepare(
738 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
739 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
740 WHERE items.barcode = ?"
742 $sth->execute($barcode);
744 my $data = $sth->fetchrow_hashref;
751 $isbd = &GetISBDView($biblionumber);
753 Return the ISBD view which can be included in opac and intranet
758 my ( $biblionumber, $template ) = @_;
759 my $record = GetMarcBiblio($biblionumber, 1);
760 return undef unless defined $record;
761 my $itemtype = &GetFrameworkCode($biblionumber);
762 my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch", $itemtype );
763 my $tagslib = &GetMarcStructure( 1, $itemtype );
765 my $ISBD = C4::Context->preference('isbd');
770 foreach my $isbdfield ( split( /#/, $bloc ) ) {
772 # $isbdfield= /(.?.?.?)/;
773 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
774 my $fieldvalue = $1 || 0;
775 my $subfvalue = $2 || "";
777 my $analysestring = $4;
780 # warn "==> $1 / $2 / $3 / $4";
781 # my $fieldvalue=substr($isbdfield,0,3);
782 if ( $fieldvalue > 0 ) {
783 my $hasputtextbefore = 0;
784 my @fieldslist = $record->field($fieldvalue);
785 @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf );
787 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
788 # warn "FV : $fieldvalue";
789 if ( $subfvalue ne "" ) {
790 foreach my $field (@fieldslist) {
791 foreach my $subfield ( $field->subfield($subfvalue) ) {
792 my $calculated = $analysestring;
793 my $tag = $field->tag();
796 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib );
797 my $tagsubf = $tag . $subfvalue;
798 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
799 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
801 # field builded, store the result
802 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
803 $blocres .= $textbefore;
804 $hasputtextbefore = 1;
807 # remove punctuation at start
808 $calculated =~ s/^( |;|:|\.|-)*//g;
809 $blocres .= $calculated;
814 $blocres .= $textafter if $hasputtextbefore;
816 foreach my $field (@fieldslist) {
817 my $calculated = $analysestring;
818 my $tag = $field->tag();
821 my @subf = $field->subfields;
822 for my $i ( 0 .. $#subf ) {
823 my $valuecode = $subf[$i][1];
824 my $subfieldcode = $subf[$i][0];
825 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib );
826 my $tagsubf = $tag . $subfieldcode;
828 $calculated =~ s/ # replace all {{}} codes by the value code.
829 \{\{$tagsubf\}\} # catch the {{actualcode}}
831 $valuecode # replace by the value code
834 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
835 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
838 # field builded, store the result
839 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
840 $blocres .= $textbefore;
841 $hasputtextbefore = 1;
844 # remove punctuation at start
845 $calculated =~ s/^( |;|:|\.|-)*//g;
846 $blocres .= $calculated;
849 $blocres .= $textafter if $hasputtextbefore;
852 $blocres .= $isbdfield;
857 $res =~ s/\{(.*?)\}//g;
859 $res =~ s/\n/<br\/>/g;
869 ( $count, @results ) = &GetBiblio($biblionumber);
874 my ($biblionumber) = @_;
875 my $dbh = C4::Context->dbh;
876 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
879 $sth->execute($biblionumber);
880 while ( my $data = $sth->fetchrow_hashref ) {
881 $results[$count] = $data;
885 return ( $count, @results );
888 =head2 GetBiblioItemInfosOf
890 GetBiblioItemInfosOf(@biblioitemnumbers);
894 sub GetBiblioItemInfosOf {
895 my @biblioitemnumbers = @_;
898 SELECT biblioitemnumber,
902 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
904 return get_infos_of( $query, 'biblioitemnumber' );
907 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
909 =head2 GetMarcStructure
911 $res = GetMarcStructure($forlibrarian,$frameworkcode);
913 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
914 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
915 $frameworkcode : the framework code to read
919 # cache for results of GetMarcStructure -- needed
921 our $marc_structure_cache;
923 sub GetMarcStructure {
924 my ( $forlibrarian, $frameworkcode ) = @_;
925 my $dbh = C4::Context->dbh;
926 $frameworkcode = "" unless $frameworkcode;
928 if ( defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode} ) {
929 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
932 # my $sth = $dbh->prepare(
933 # "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
934 # $sth->execute($frameworkcode);
935 # my ($total) = $sth->fetchrow;
936 # $frameworkcode = "" unless ( $total > 0 );
937 my $sth = $dbh->prepare(
938 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
939 FROM marc_tag_structure
940 WHERE frameworkcode=?
943 $sth->execute($frameworkcode);
944 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
946 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
947 $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
948 $res->{$tag}->{tab} = "";
949 $res->{$tag}->{mandatory} = $mandatory;
950 $res->{$tag}->{repeatable} = $repeatable;
953 $sth = $dbh->prepare(
954 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
955 FROM marc_subfield_structure
956 WHERE frameworkcode=?
957 ORDER BY tagfield,tagsubfield
961 $sth->execute($frameworkcode);
964 my $authorised_value;
975 ( $tag, $subfield, $liblibrarian, $libopac, $tab, $mandatory, $repeatable, $authorised_value,
976 $authtypecode, $value_builder, $kohafield, $seealso, $hidden, $isurl, $link, $defaultvalue
980 $res->{$tag}->{$subfield}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
981 $res->{$tag}->{$subfield}->{tab} = $tab;
982 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
983 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
984 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
985 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
986 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
987 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
988 $res->{$tag}->{$subfield}->{seealso} = $seealso;
989 $res->{$tag}->{$subfield}->{hidden} = $hidden;
990 $res->{$tag}->{$subfield}->{isurl} = $isurl;
991 $res->{$tag}->{$subfield}->{'link'} = $link;
992 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
995 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
1000 =head2 GetUsedMarcStructure
1002 The same function as GetMarcStructure except it just takes field
1003 in tab 0-9. (used field)
1005 my $results = GetUsedMarcStructure($frameworkcode);
1007 C<$results> is a ref to an array which each case containts a ref
1008 to a hash which each keys is the columns from marc_subfield_structure
1010 C<$frameworkcode> is the framework code.
1014 sub GetUsedMarcStructure($) {
1015 my $frameworkcode = shift || '';
1018 FROM marc_subfield_structure
1020 AND frameworkcode = ?
1021 ORDER BY tagfield, tagsubfield
1023 my $sth = C4::Context->dbh->prepare($query);
1024 $sth->execute($frameworkcode);
1025 return $sth->fetchall_arrayref( {} );
1028 =head2 GetMarcFromKohaField
1030 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1032 Returns the MARC fields & subfields mapped to the koha field
1033 for the given frameworkcode
1037 sub GetMarcFromKohaField {
1038 my ( $kohafield, $frameworkcode ) = @_;
1039 return (0, undef) unless $kohafield and defined $frameworkcode;
1040 my $relations = C4::Context->marcfromkohafield;
1041 if ( my $mf = $relations->{$frameworkcode}->{$kohafield} ) {
1047 =head2 GetMarcBiblio
1049 my $record = GetMarcBiblio($biblionumber, [$embeditems]);
1051 Returns MARC::Record representing bib identified by
1052 C<$biblionumber>. If no bib exists, returns undef.
1053 C<$embeditems>. If set to true, items data are included.
1054 The MARC record contains biblio data, and items data if $embeditems is set to true.
1059 my $biblionumber = shift;
1060 my $embeditems = shift || 0;
1061 my $dbh = C4::Context->dbh;
1062 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1063 $sth->execute($biblionumber);
1064 my $row = $sth->fetchrow_hashref;
1065 my $marcxml = StripNonXmlChars( $row->{'marcxml'} );
1066 MARC::File::XML->default_record_format( C4::Context->preference('marcflavour') );
1067 my $record = MARC::Record->new();
1070 $record = eval { MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour') ) };
1071 if ($@) { warn " problem with :$biblionumber : $@ \n$marcxml"; }
1072 return unless $record;
1074 C4::Biblio::_koha_marc_update_bib_ids($record, '', $biblionumber, $biblionumber);
1075 C4::Biblio::EmbedItemsInMarcBiblio($record, $biblionumber) if ($embeditems);
1085 my $marcxml = GetXmlBiblio($biblionumber);
1087 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1088 The XML contains both biblio & item datas
1093 my ($biblionumber) = @_;
1094 my $dbh = C4::Context->dbh;
1095 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1096 $sth->execute($biblionumber);
1097 my ($marcxml) = $sth->fetchrow;
1101 =head2 GetCOinSBiblio
1103 my $coins = GetCOinSBiblio($record);
1105 Returns the COinS (a span) which can be included in a biblio record
1109 sub GetCOinSBiblio {
1112 # get the coin format
1116 my $pos7 = substr $record->leader(), 7, 1;
1117 my $pos6 = substr $record->leader(), 6, 1;
1120 my ( $aulast, $aufirst ) = ( '', '' );
1129 my $titletype = 'b';
1131 # For the purposes of generating COinS metadata, LDR/06-07 can be
1132 # considered the same for UNIMARC and MARC21
1137 'b' => 'manuscript',
1139 'd' => 'manuscript',
1143 'i' => 'audioRecording',
1144 'j' => 'audioRecording',
1147 'm' => 'computerProgram',
1152 'a' => 'journalArticle',
1156 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
1158 if ( $genre eq 'book' ) {
1159 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1162 ##### We must transform mtx to a valable mtx and document type ####
1163 if ( $genre eq 'book' ) {
1165 } elsif ( $genre eq 'journal' ) {
1168 } elsif ( $genre eq 'journalArticle' ) {
1176 $genre = ( $mtx eq 'dc' ) ? "&rft.type=$genre" : "&rft.genre=$genre";
1178 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
1181 $aulast = $record->subfield( '700', 'a' ) || '';
1182 $aufirst = $record->subfield( '700', 'b' ) || '';
1183 $oauthors = "&rft.au=$aufirst $aulast";
1186 if ( $record->field('200') ) {
1187 for my $au ( $record->field('200')->subfield('g') ) {
1188 $oauthors .= "&rft.au=$au";
1193 ? "&rft.title=" . $record->subfield( '200', 'a' )
1194 : "&rft.title=" . $record->subfield( '200', 'a' ) . "&rft.btitle=" . $record->subfield( '200', 'a' );
1195 $pubyear = $record->subfield( '210', 'd' ) || '';
1196 $publisher = $record->subfield( '210', 'c' ) || '';
1197 $isbn = $record->subfield( '010', 'a' ) || '';
1198 $issn = $record->subfield( '011', 'a' ) || '';
1201 # MARC21 need some improve
1204 if ( $record->field('100') ) {
1205 $oauthors .= "&rft.au=" . $record->subfield( '100', 'a' );
1209 if ( $record->field('700') ) {
1210 for my $au ( $record->field('700')->subfield('a') ) {
1211 $oauthors .= "&rft.au=$au";
1214 $title = "&rft." . $titletype . "title=" . $record->subfield( '245', 'a' );
1215 $subtitle = $record->subfield( '245', 'b' ) || '';
1216 $title .= $subtitle;
1217 if ($titletype eq 'a') {
1218 $pubyear = $record->field('008') || '';
1219 $pubyear = substr($pubyear->data(), 7, 4) if $pubyear;
1220 $isbn = $record->subfield( '773', 'z' ) || '';
1221 $issn = $record->subfield( '773', 'x' ) || '';
1222 if ($mtx eq 'journal') {
1223 $title .= "&rft.title=" . (($record->subfield( '773', 't' ) || $record->subfield( '773', 'a')));
1225 $title .= "&rft.btitle=" . (($record->subfield( '773', 't' ) || $record->subfield( '773', 'a')) || '');
1227 foreach my $rel ($record->subfield( '773', 'g' )) {
1234 $pubyear = $record->subfield( '260', 'c' ) || '';
1235 $publisher = $record->subfield( '260', 'b' ) || '';
1236 $isbn = $record->subfield( '020', 'a' ) || '';
1237 $issn = $record->subfield( '022', 'a' ) || '';
1242 "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";
1243 $coins_value =~ s/(\ |&[^a])/\+/g;
1244 $coins_value =~ s/\"/\"\;/g;
1246 #<!-- 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="
1248 return $coins_value;
1254 return the prices in accordance with the Marc format.
1258 my ( $record, $marcflavour ) = @_;
1262 if ( $marcflavour eq "MARC21" ) {
1263 @listtags = ('345', '020');
1265 } elsif ( $marcflavour eq "UNIMARC" ) {
1266 @listtags = ('345', '010');
1272 for my $field ( $record->field(@listtags) ) {
1273 for my $subfield_value ($field->subfield($subfield)){
1275 return $subfield_value if ($subfield_value);
1278 return 0; # no price found
1281 =head2 GetMarcQuantity
1283 return the quantity of a book. Used in acquisition only, when importing a file an iso2709 from a bookseller
1284 Warning : this is not really in the marc standard. In Unimarc, Electre (the most widely used bookseller) use the 969$a
1288 sub GetMarcQuantity {
1289 my ( $record, $marcflavour ) = @_;
1293 if ( $marcflavour eq "MARC21" ) {
1295 } elsif ( $marcflavour eq "UNIMARC" ) {
1296 @listtags = ('969');
1302 for my $field ( $record->field(@listtags) ) {
1303 for my $subfield_value ($field->subfield($subfield)){
1305 if ($subfield_value) {
1306 # in France, the cents separator is the , but sometimes, ppl use a .
1307 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
1308 $subfield_value =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
1309 return $subfield_value;
1313 return 0; # no price found
1317 =head2 GetAuthorisedValueDesc
1319 my $subfieldvalue =get_authorised_value_desc(
1320 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category, $opac);
1322 Retrieve the complete description for a given authorised value.
1324 Now takes $category and $value pair too.
1326 my $auth_value_desc =GetAuthorisedValueDesc(
1327 '','', 'DVD' ,'','','CCODE');
1329 If the optional $opac parameter is set to a true value, displays OPAC
1330 descriptions rather than normal ones when they exist.
1334 sub GetAuthorisedValueDesc {
1335 my ( $tag, $subfield, $value, $framework, $tagslib, $category, $opac ) = @_;
1336 my $dbh = C4::Context->dbh;
1340 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1343 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1344 return C4::Branch::GetBranchName($value);
1348 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1349 return getitemtypeinfo($value)->{description};
1352 #---- "true" authorized value
1353 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1356 if ( $category ne "" ) {
1357 my $sth = $dbh->prepare( "SELECT lib, lib_opac FROM authorised_values WHERE category = ? AND authorised_value = ?" );
1358 $sth->execute( $category, $value );
1359 my $data = $sth->fetchrow_hashref;
1360 return ( $opac && $data->{'lib_opac'} ) ? $data->{'lib_opac'} : $data->{'lib'};
1362 return $value; # if nothing is found return the original value
1366 =head2 GetMarcControlnumber
1368 $marccontrolnumber = GetMarcControlnumber($record,$marcflavour);
1370 Get the control number / record Identifier from the MARC record and return it.
1374 sub GetMarcControlnumber {
1375 my ( $record, $marcflavour ) = @_;
1376 my $controlnumber = "";
1377 # Control number or Record identifier are the same field in MARC21 and UNIMARC
1378 # Keep $marcflavour for possible later use
1379 if ($marcflavour eq "MARC21" || $marcflavour eq "UNIMARC") {
1380 my $controlnumberField = $record->field('001');
1381 if ($controlnumberField) {
1382 $controlnumber = $controlnumberField->data();
1385 return $controlnumber;
1390 $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
1392 Get all ISBNs from the MARC record and returns them in an array.
1393 ISBNs stored in differents places depending on MARC flavour
1398 my ( $record, $marcflavour ) = @_;
1400 if ( $marcflavour eq "UNIMARC" ) {
1402 } else { # assume marc21 if not unimarc
1409 foreach my $field ( $record->field($scope) ) {
1410 my $value = $field->as_string();
1411 if ( $isbn ne "" ) {
1412 $marcisbn = { marcisbn => $isbn, };
1413 push @marcisbns, $marcisbn;
1416 if ( $isbn ne $value ) {
1417 $isbn = $isbn . " " . $value;
1422 $marcisbn = { marcisbn => $isbn };
1423 push @marcisbns, $marcisbn; #load last tag into array
1430 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1432 Get all notes from the MARC record and returns them in an array.
1433 The note are stored in differents places depending on MARC flavour
1438 my ( $record, $marcflavour ) = @_;
1440 if ( $marcflavour eq "UNIMARC" ) {
1442 } else { # assume marc21 if not unimarc
1449 foreach my $field ( $record->field($scope) ) {
1450 my $value = $field->as_string();
1451 if ( $note ne "" ) {
1452 $marcnote = { marcnote => $note, };
1453 push @marcnotes, $marcnote;
1456 if ( $note ne $value ) {
1457 $note = $note . " " . $value;
1462 $marcnote = { marcnote => $note };
1463 push @marcnotes, $marcnote; #load last tag into array
1466 } # end GetMarcNotes
1468 =head2 GetMarcSubjects
1470 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1472 Get all subjects from the MARC record and returns them in an array.
1473 The subjects are stored in differents places depending on MARC flavour
1477 sub GetMarcSubjects {
1478 my ( $record, $marcflavour ) = @_;
1479 my ( $mintag, $maxtag );
1480 if ( $marcflavour eq "UNIMARC" ) {
1483 } else { # assume marc21 if not unimarc
1493 my $subject_limit = C4::Context->preference("TraceCompleteSubfields") ? 'su,complete-subfield' : 'su';
1495 foreach my $field ( $record->field('6..') ) {
1496 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1498 my @subfields = $field->subfields();
1502 # if there is an authority link, build the link with an= subfield9
1504 for my $subject_subfield (@subfields) {
1506 # don't load unimarc subfields 3,4,5
1507 next if ( ( $marcflavour eq "UNIMARC" ) and ( $subject_subfield->[0] =~ /2|3|4|5/ ) );
1509 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1510 next if ( ( $marcflavour eq "MARC21" ) and ( $subject_subfield->[0] =~ /2/ ) );
1511 my $code = $subject_subfield->[0];
1512 my $value = $subject_subfield->[1];
1513 my $linkvalue = $value;
1514 $linkvalue =~ s/(\(|\))//g;
1516 if ( $counter != 0 ) {
1517 $operator = ' and ';
1521 @link_loop = ( { 'limit' => 'an', link => "$linkvalue" } );
1523 if ( not $found9 ) {
1524 push @link_loop, { 'limit' => $subject_limit, link => $linkvalue, operator => $operator };
1527 if ( $counter != 0 ) {
1528 $separator = C4::Context->preference('authoritysep');
1532 my @this_link_loop = @link_loop;
1533 push @subfields_loop, { code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator } unless ( $subject_subfield->[0] eq 9 );
1537 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1540 return \@marcsubjects;
1541 } #end getMARCsubjects
1543 =head2 GetMarcAuthors
1545 authors = GetMarcAuthors($record,$marcflavour);
1547 Get all authors from the MARC record and returns them in an array.
1548 The authors are stored in differents places depending on MARC flavour
1552 sub GetMarcAuthors {
1553 my ( $record, $marcflavour ) = @_;
1554 my ( $mintag, $maxtag );
1556 # tagslib useful for UNIMARC author reponsabilities
1558 &GetMarcStructure( 1, '' ); # FIXME : we don't have the framework available, we take the default framework. May be buggy on some setups, will be usually correct.
1559 if ( $marcflavour eq "UNIMARC" ) {
1562 } elsif ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) { # assume marc21 or normarc if not unimarc
1570 foreach my $field ( $record->fields ) {
1571 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1574 my @subfields = $field->subfields();
1577 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1578 my $subfield9 = $field->subfield('9');
1579 for my $authors_subfield (@subfields) {
1581 # don't load unimarc subfields 3, 5
1582 next if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /3|5/ ) );
1583 my $subfieldcode = $authors_subfield->[0];
1584 my $value = $authors_subfield->[1];
1585 my $linkvalue = $value;
1586 $linkvalue =~ s/(\(|\))//g;
1588 if ( $count_auth != 0 ) {
1589 $operator = ' and ';
1592 # if we have an authority link, use that as the link, otherwise use standard searching
1594 @link_loop = ( { 'limit' => 'an', link => "$subfield9" } );
1597 # reset $linkvalue if UNIMARC author responsibility
1598 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] eq "4" ) ) {
1599 $linkvalue = "(" . GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) . ")";
1601 push @link_loop, { 'limit' => 'au', link => $linkvalue, operator => $operator };
1603 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib )
1604 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /4/ ) );
1605 my @this_link_loop = @link_loop;
1607 if ( $count_auth != 0 ) {
1608 $separator = C4::Context->preference('authoritysep');
1610 push @subfields_loop,
1611 { tag => $field->tag(),
1612 code => $subfieldcode,
1614 link_loop => \@this_link_loop,
1615 separator => $separator
1617 unless ( $authors_subfield->[0] eq '9' );
1620 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1622 return \@marcauthors;
1627 $marcurls = GetMarcUrls($record,$marcflavour);
1629 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1630 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1635 my ( $record, $marcflavour ) = @_;
1638 for my $field ( $record->field('856') ) {
1640 for my $note ( $field->subfield('z') ) {
1641 push @notes, { note => $note };
1643 my @urls = $field->subfield('u');
1644 foreach my $url (@urls) {
1646 if ( $marcflavour eq 'MARC21' ) {
1647 my $s3 = $field->subfield('3');
1648 my $link = $field->subfield('y');
1649 unless ( $url =~ /^\w+:/ ) {
1650 if ( $field->indicator(1) eq '7' ) {
1651 $url = $field->subfield('2') . "://" . $url;
1652 } elsif ( $field->indicator(1) eq '1' ) {
1653 $url = 'ftp://' . $url;
1656 # properly, this should be if ind1=4,
1657 # however we will assume http protocol since we're building a link.
1658 $url = 'http://' . $url;
1662 # TODO handle ind 2 (relationship)
1667 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1668 $marcurl->{'part'} = $s3 if ($link);
1669 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1671 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1672 $marcurl->{'MARCURL'} = $url;
1674 push @marcurls, $marcurl;
1680 =head2 GetMarcSeries
1682 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1684 Get all series from the MARC record and returns them in an array.
1685 The series are stored in differents places depending on MARC flavour
1690 my ( $record, $marcflavour ) = @_;
1691 my ( $mintag, $maxtag );
1692 if ( $marcflavour eq "UNIMARC" ) {
1695 } else { # assume marc21 if not unimarc
1705 foreach my $field ( $record->field('440'), $record->field('490') ) {
1708 #my $value = $field->subfield('a');
1709 #$marcsubjct = {MARCSUBJCT => $value,};
1710 my @subfields = $field->subfields();
1712 #warn "subfields:".join " ", @$subfields;
1715 for my $series_subfield (@subfields) {
1717 undef $volume_number;
1719 # see if this is an instance of a volume
1720 if ( $series_subfield->[0] eq 'v' ) {
1724 my $code = $series_subfield->[0];
1725 my $value = $series_subfield->[1];
1726 my $linkvalue = $value;
1727 $linkvalue =~ s/(\(|\))//g;
1728 if ( $counter != 0 ) {
1729 push @link_loop, { link => $linkvalue, operator => ' and ', };
1731 push @link_loop, { link => $linkvalue, operator => undef, };
1734 if ( $counter != 0 ) {
1735 $separator = C4::Context->preference('authoritysep');
1737 if ($volume_number) {
1738 push @subfields_loop, { volumenum => $value };
1740 if ( $series_subfield->[0] ne '9' ) {
1741 push @subfields_loop, {
1744 link_loop => \@link_loop,
1745 separator => $separator,
1746 volumenum => $volume_number,
1752 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1754 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1755 #push @marcsubjcts, $marcsubjct;
1759 my $marcseriessarray = \@marcseries;
1760 return $marcseriessarray;
1761 } #end getMARCseriess
1765 $marchostsarray = GetMarcHosts($record,$marcflavour);
1767 Get all host records (773s MARC21, 461 UNIMARC) from the MARC record and returns them in an array.
1772 my ( $record, $marcflavour ) = @_;
1773 my ( $tag,$title_subf,$bibnumber_subf,$itemnumber_subf);
1774 $marcflavour ||="MARC21";
1775 if ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) {
1778 $bibnumber_subf ="0";
1779 $itemnumber_subf='9';
1781 elsif ($marcflavour eq "UNIMARC") {
1784 $bibnumber_subf ="0";
1785 $itemnumber_subf='9';
1790 foreach my $field ( $record->field($tag)) {
1794 my $hostbiblionumber = $field->subfield("$bibnumber_subf");
1795 my $hosttitle = $field->subfield($title_subf);
1796 my $hostitemnumber=$field->subfield($itemnumber_subf);
1797 push @fields_loop, { hostbiblionumber => $hostbiblionumber, hosttitle => $hosttitle, hostitemnumber => $hostitemnumber};
1798 push @marchosts, { MARCHOSTS_FIELDS_LOOP => \@fields_loop };
1801 my $marchostsarray = \@marchosts;
1802 return $marchostsarray;
1805 =head2 GetFrameworkCode
1807 $frameworkcode = GetFrameworkCode( $biblionumber )
1811 sub GetFrameworkCode {
1812 my ($biblionumber) = @_;
1813 my $dbh = C4::Context->dbh;
1814 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1815 $sth->execute($biblionumber);
1816 my ($frameworkcode) = $sth->fetchrow;
1817 return $frameworkcode;
1820 =head2 TransformKohaToMarc
1822 $record = TransformKohaToMarc( $hash )
1824 This function builds partial MARC::Record from a hash
1825 Hash entries can be from biblio or biblioitems.
1827 This function is called in acquisition module, to create a basic catalogue
1828 entry from user entry
1833 sub TransformKohaToMarc {
1835 my $record = MARC::Record->new();
1836 SetMarcUnicodeFlag( $record, C4::Context->preference("marcflavour") );
1837 my $db_to_marc = C4::Context->marcfromkohafield;
1838 while ( my ($name, $value) = each %$hash ) {
1839 next unless my $dtm = $db_to_marc->{''}->{$name};
1840 my ($tag, $letter) = @$dtm;
1841 foreach my $value ( split(/\s?\|\s?/, $value, -1) ) {
1842 if ( my $field = $record->field($tag) ) {
1843 $field->add_subfields( $letter => $value );
1846 $record->insert_fields_ordered( MARC::Field->new(
1847 $tag, " ", " ", $letter => $value ) );
1855 =head2 PrepHostMarcField
1857 $hostfield = PrepHostMarcField ( $hostbiblionumber,$hostitemnumber,$marcflavour )
1859 This function returns a host field populated with data from the host record, the field can then be added to an analytical record
1863 sub PrepHostMarcField {
1864 my ($hostbiblionumber,$hostitemnumber, $marcflavour) = @_;
1865 $marcflavour ||="MARC21";
1867 my $hostrecord = GetMarcBiblio($hostbiblionumber);
1868 my $item = C4::Items::GetItem($hostitemnumber);
1871 if ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) {
1875 if ($hostrecord->subfield('100','a')){
1876 $mainentry = $hostrecord->subfield('100','a');
1877 } elsif ($hostrecord->subfield('110','a')){
1878 $mainentry = $hostrecord->subfield('110','a');
1880 $mainentry = $hostrecord->subfield('111','a');
1883 # qualification info
1885 if (my $field260 = $hostrecord->field('260')){
1886 $qualinfo = $field260->as_string( 'abc' );
1891 my $ed = $hostrecord->subfield('250','a');
1892 my $barcode = $item->{'barcode'};
1893 my $title = $hostrecord->subfield('245','a');
1895 # record control number, 001 with 003 and prefix
1897 if ($hostrecord->field('001')){
1898 $recctrlno = $hostrecord->field('001')->data();
1899 if ($hostrecord->field('003')){
1900 $recctrlno = '('.$hostrecord->field('003')->data().')'.$recctrlno;
1905 my $issn = $hostrecord->subfield('022','a');
1906 my $isbn = $hostrecord->subfield('020','a');
1909 $hostmarcfield = MARC::Field->new(
1911 '0' => $hostbiblionumber,
1912 '9' => $hostitemnumber,
1922 } elsif ($marcflavour eq "UNIMARC") {
1923 $hostmarcfield = MARC::Field->new(
1925 '0' => $hostbiblionumber,
1926 't' => $hostrecord->subfield('200','a'),
1927 '9' => $hostitemnumber
1931 return $hostmarcfield;
1934 =head2 TransformHtmlToXml
1936 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator,
1937 $ind_tag, $auth_type )
1939 $auth_type contains :
1943 =item - nothing : rebuild a biblio. In UNIMARC the encoding is in 100$a pos 26/27
1945 =item - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1947 =item - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1953 sub TransformHtmlToXml {
1954 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1955 my $xml = MARC::File::XML::header('UTF-8');
1956 $xml .= "<record>\n";
1957 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1958 MARC::File::XML->default_record_format($auth_type);
1960 # in UNIMARC, field 100 contains the encoding
1961 # check that there is one, otherwise the
1962 # MARC::Record->new_from_xml will fail (and Koha will die)
1963 my $unimarc_and_100_exist = 0;
1964 $unimarc_and_100_exist = 1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1969 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1971 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a" ) {
1973 # if we have a 100 field and it's values are not correct, skip them.
1974 # if we don't have any valid 100 field, we will create a default one at the end
1975 my $enc = substr( @$values[$i], 26, 2 );
1976 if ( $enc eq '01' or $enc eq '50' or $enc eq '03' ) {
1977 $unimarc_and_100_exist = 1;
1982 @$values[$i] =~ s/&/&/g;
1983 @$values[$i] =~ s/</</g;
1984 @$values[$i] =~ s/>/>/g;
1985 @$values[$i] =~ s/"/"/g;
1986 @$values[$i] =~ s/'/'/g;
1988 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1989 # utf8::decode( @$values[$i] );
1991 if ( ( @$tags[$i] ne $prevtag ) ) {
1992 $j++ unless ( @$tags[$i] eq "" );
1993 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
1994 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
1995 my $ind1 = _default_ind_to_space($indicator1);
1997 if ( @$indicator[$j] ) {
1998 $ind2 = _default_ind_to_space($indicator2);
2000 warn "Indicator in @$tags[$i] is empty";
2004 $xml .= "</datafield>\n";
2005 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2006 && ( @$values[$i] ne "" ) ) {
2007 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2008 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2014 if ( @$values[$i] ne "" ) {
2017 if ( @$tags[$i] eq "000" ) {
2018 $xml .= "<leader>@$values[$i]</leader>\n";
2021 # rest of the fixed fields
2022 } elsif ( @$tags[$i] < 10 ) {
2023 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2026 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2027 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2032 } else { # @$tags[$i] eq $prevtag
2033 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
2034 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
2035 my $ind1 = _default_ind_to_space($indicator1);
2037 if ( @$indicator[$j] ) {
2038 $ind2 = _default_ind_to_space($indicator2);
2040 warn "Indicator in @$tags[$i] is empty";
2043 if ( @$values[$i] eq "" ) {
2046 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2049 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2052 $prevtag = @$tags[$i];
2054 $xml .= "</datafield>\n" if $xml =~ m/<datafield/;
2055 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist ) {
2057 # warn "SETTING 100 for $auth_type";
2058 my $string = strftime( "%Y%m%d", localtime(time) );
2060 # set 50 to position 26 is biblios, 13 if authorities
2062 $pos = 13 if $auth_type eq 'UNIMARCAUTH';
2063 $string = sprintf( "%-*s", 35, $string );
2064 substr( $string, $pos, 6, "50" );
2065 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2066 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2067 $xml .= "</datafield>\n";
2069 $xml .= "</record>\n";
2070 $xml .= MARC::File::XML::footer();
2074 =head2 _default_ind_to_space
2076 Passed what should be an indicator returns a space
2077 if its undefined or zero length
2081 sub _default_ind_to_space {
2083 if ( !defined $s || $s eq q{} ) {
2089 =head2 TransformHtmlToMarc
2091 L<$record> = TransformHtmlToMarc(L<$cgi>)
2092 L<$cgi> is the CGI object which containts the values for subfields
2094 'tag_010_indicator1_531951' ,
2095 'tag_010_indicator2_531951' ,
2096 'tag_010_code_a_531951_145735' ,
2097 'tag_010_subfield_a_531951_145735' ,
2098 'tag_200_indicator1_873510' ,
2099 'tag_200_indicator2_873510' ,
2100 'tag_200_code_a_873510_673465' ,
2101 'tag_200_subfield_a_873510_673465' ,
2102 'tag_200_code_b_873510_704318' ,
2103 'tag_200_subfield_b_873510_704318' ,
2104 'tag_200_code_e_873510_280822' ,
2105 'tag_200_subfield_e_873510_280822' ,
2106 'tag_200_code_f_873510_110730' ,
2107 'tag_200_subfield_f_873510_110730' ,
2109 L<$record> is the MARC::Record object.
2113 sub TransformHtmlToMarc {
2116 my @params = $cgi->param();
2118 # explicitly turn on the UTF-8 flag for all
2119 # 'tag_' parameters to avoid incorrect character
2120 # conversion later on
2121 my $cgi_params = $cgi->Vars;
2122 foreach my $param_name ( keys %$cgi_params ) {
2123 if ( $param_name =~ /^tag_/ ) {
2124 my $param_value = $cgi_params->{$param_name};
2125 if ( utf8::decode($param_value) ) {
2126 $cgi_params->{$param_name} = $param_value;
2129 # FIXME - need to do something if string is not valid UTF-8
2133 # creating a new record
2134 my $record = MARC::Record->new();
2137 #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!
2138 while ( $params[$i] ) { # browse all CGI params
2139 my $param = $params[$i];
2142 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2143 if ( $param eq 'biblionumber' ) {
2144 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
2145 if ( $biblionumbertagfield < 10 ) {
2146 $newfield = MARC::Field->new( $biblionumbertagfield, $cgi->param($param), );
2148 $newfield = MARC::Field->new( $biblionumbertagfield, '', '', "$biblionumbertagsubfield" => $cgi->param($param), );
2150 push @fields, $newfield if ($newfield);
2151 } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..."
2154 my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) );
2155 my $ind2 = _default_ind_to_space( substr( $cgi->param( $params[ $i + 1 ] ), 0, 1 ) );
2159 if ( $tag < 10 ) { # no code for theses fields
2160 # in MARC editor, 000 contains the leader.
2161 if ( $tag eq '000' ) {
2162 # Force a fake leader even if not provided to avoid crashing
2163 # during decoding MARC record containing UTF-8 characters
2165 length( $cgi->param($params[$j+1]) ) == 24
2166 ? $cgi->param( $params[ $j + 1 ] )
2170 # between 001 and 009 (included)
2171 } elsif ( $cgi->param( $params[ $j + 1 ] ) ne '' ) {
2172 $newfield = MARC::Field->new( $tag, $cgi->param( $params[ $j + 1 ] ), );
2175 # > 009, deal with subfields
2177 # browse subfields for this tag (reason for _code_ match)
2178 while(defined $params[$j] && $params[$j] =~ /_code_/) {
2179 last unless defined $params[$j+1];
2180 #if next param ne subfield, then it was probably empty
2181 #try next param by incrementing j
2182 if($params[$j+1]!~/_subfield_/) {$j++; next; }
2183 my $fval= $cgi->param($params[$j+1]);
2184 #check if subfield value not empty and field exists
2185 if($fval ne '' && $newfield) {
2186 $newfield->add_subfields( $cgi->param($params[$j]) => $fval);
2188 elsif($fval ne '') {
2189 $newfield = MARC::Field->new( $tag, $ind1, $ind2, $cgi->param($params[$j]) => $fval );
2193 $i= $j-1; #update i for outer loop accordingly
2195 push @fields, $newfield if ($newfield);
2200 $record->append_fields(@fields);
2204 # cache inverted MARC field map
2205 our $inverted_field_map;
2207 =head2 TransformMarcToKoha
2209 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2211 Extract data from a MARC bib record into a hashref representing
2212 Koha biblio, biblioitems, and items fields.
2216 sub TransformMarcToKoha {
2217 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
2220 $limit_table = $limit_table || 0;
2221 $frameworkcode = '' unless defined $frameworkcode;
2223 unless ( defined $inverted_field_map ) {
2224 $inverted_field_map = _get_inverted_marc_field_map();
2228 if ( defined $limit_table && $limit_table eq 'items' ) {
2229 $tables{'items'} = 1;
2231 $tables{'items'} = 1;
2232 $tables{'biblio'} = 1;
2233 $tables{'biblioitems'} = 1;
2236 # traverse through record
2237 MARCFIELD: foreach my $field ( $record->fields() ) {
2238 my $tag = $field->tag();
2239 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2240 if ( $field->is_control_field() ) {
2241 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2242 ENTRY: foreach my $entry ( @{$kohafields} ) {
2243 my ( $subfield, $table, $column ) = @{$entry};
2244 next ENTRY unless exists $tables{$table};
2245 my $key = _disambiguate( $table, $column );
2246 if ( $result->{$key} ) {
2247 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $field->data() eq "" ) ) {
2248 $result->{$key} .= " | " . $field->data();
2251 $result->{$key} = $field->data();
2256 # deal with subfields
2257 MARCSUBFIELD: foreach my $sf ( $field->subfields() ) {
2258 my $code = $sf->[0];
2259 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2260 my $value = $sf->[1];
2261 SFENTRY: foreach my $entry ( @{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} } ) {
2262 my ( $table, $column ) = @{$entry};
2263 next SFENTRY unless exists $tables{$table};
2264 my $key = _disambiguate( $table, $column );
2265 if ( $result->{$key} ) {
2266 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $value eq "" ) ) {
2267 $result->{$key} .= " | " . $value;
2270 $result->{$key} = $value;
2277 # modify copyrightdate to keep only the 1st year found
2278 if ( exists $result->{'copyrightdate'} ) {
2279 my $temp = $result->{'copyrightdate'};
2280 $temp =~ m/c(\d\d\d\d)/;
2281 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2282 $result->{'copyrightdate'} = $1;
2283 } else { # if no cYYYY, get the 1st date.
2284 $temp =~ m/(\d\d\d\d)/;
2285 $result->{'copyrightdate'} = $1;
2289 # modify publicationyear to keep only the 1st year found
2290 if ( exists $result->{'publicationyear'} ) {
2291 my $temp = $result->{'publicationyear'};
2292 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2293 $result->{'publicationyear'} = $1;
2294 } else { # if no cYYYY, get the 1st date.
2295 $temp =~ m/(\d\d\d\d)/;
2296 $result->{'publicationyear'} = $1;
2303 sub _get_inverted_marc_field_map {
2305 my $relations = C4::Context->marcfromkohafield;
2307 foreach my $frameworkcode ( keys %{$relations} ) {
2308 foreach my $kohafield ( keys %{ $relations->{$frameworkcode} } ) {
2309 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2310 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2311 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2312 my ( $table, $column ) = split /[.]/, $kohafield, 2;
2313 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2314 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2320 =head2 _disambiguate
2322 $newkey = _disambiguate($table, $field);
2324 This is a temporary hack to distinguish between the
2325 following sets of columns when using TransformMarcToKoha.
2327 items.cn_source & biblioitems.cn_source
2328 items.cn_sort & biblioitems.cn_sort
2330 Columns that are currently NOT distinguished (FIXME
2331 due to lack of time to fully test) are:
2333 biblio.notes and biblioitems.notes
2338 FIXME - this is necessary because prefixing each column
2339 name with the table name would require changing lots
2340 of code and templates, and exposing more of the DB
2341 structure than is good to the UI templates, particularly
2342 since biblio and bibloitems may well merge in a future
2343 version. In the future, it would also be good to
2344 separate DB access and UI presentation field names
2349 sub CountItemsIssued {
2350 my ($biblionumber) = @_;
2351 my $dbh = C4::Context->dbh;
2352 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2353 $sth->execute($biblionumber);
2354 my $row = $sth->fetchrow_hashref();
2355 return $row->{'issuedCount'};
2359 my ( $table, $column ) = @_;
2360 if ( $column eq "cn_sort" or $column eq "cn_source" ) {
2361 return $table . '.' . $column;
2368 =head2 get_koha_field_from_marc
2370 $result->{_disambiguate($table, $field)} =
2371 get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2373 Internal function to map data from the MARC record to a specific non-MARC field.
2374 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2378 sub get_koha_field_from_marc {
2379 my ( $koha_table, $koha_column, $record, $frameworkcode ) = @_;
2380 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table . '.' . $koha_column, $frameworkcode );
2382 foreach my $field ( $record->field($tagfield) ) {
2383 if ( $field->tag() < 10 ) {
2385 $kohafield .= " | " . $field->data();
2387 $kohafield = $field->data();
2390 if ( $field->subfields ) {
2391 my @subfields = $field->subfields();
2392 foreach my $subfieldcount ( 0 .. $#subfields ) {
2393 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2395 $kohafield .= " | " . $subfields[$subfieldcount][1];
2397 $kohafield = $subfields[$subfieldcount][1];
2407 =head2 TransformMarcToKohaOneField
2409 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2413 sub TransformMarcToKohaOneField {
2415 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2416 # only the 1st will be retrieved...
2417 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2419 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $kohatable . "." . $kohafield, $frameworkcode );
2420 foreach my $field ( $record->field($tagfield) ) {
2421 if ( $field->tag() < 10 ) {
2422 if ( $result->{$kohafield} ) {
2423 $result->{$kohafield} .= " | " . $field->data();
2425 $result->{$kohafield} = $field->data();
2428 if ( $field->subfields ) {
2429 my @subfields = $field->subfields();
2430 foreach my $subfieldcount ( 0 .. $#subfields ) {
2431 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2432 if ( $result->{$kohafield} ) {
2433 $result->{$kohafield} .= " | " . $subfields[$subfieldcount][1];
2435 $result->{$kohafield} = $subfields[$subfieldcount][1];
2449 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2451 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2452 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2453 # =head2 ModZebrafiles
2455 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2459 # sub ModZebrafiles {
2461 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2465 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2466 # unless ( opendir( DIR, "$zebradir" ) ) {
2467 # warn "$zebradir not found";
2471 # my $filename = $zebradir . $biblionumber;
2474 # open( OUTPUT, ">", $filename . ".xml" );
2475 # print OUTPUT $record;
2482 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2484 $biblionumber is the biblionumber we want to index
2486 $op is specialUpdate or delete, and is used to know what we want to do
2488 $server is the server that we want to update
2490 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2491 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2494 $newRecord is the MARC::Record containing the new record. It is usefull only when NoZebra=1, and is used to know what to add to the nozebra database. (the record in mySQL being, if it exist, the previous record, the one just before the modif. We need both : the previous and the new one.
2499 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2500 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2501 my $dbh = C4::Context->dbh;
2503 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2505 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2506 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2508 if ( C4::Context->preference("NoZebra") ) {
2510 # lock the nozebra table : we will read index lines, update them in Perl process
2511 # and write everything in 1 transaction.
2512 # lock the table to avoid someone else overwriting what we are doing
2513 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2514 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2515 if ( $op eq 'specialUpdate' ) {
2517 # OK, we have to add or update the record
2518 # 1st delete (virtually, in indexes), if record actually exists
2520 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2523 # ... add the record
2524 %result = _AddBiblioNoZebra( $biblionumber, $newRecord, $server, %result );
2527 # it's a deletion, delete the record...
2528 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2529 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2532 # ok, now update the database...
2533 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2534 foreach my $key ( keys %result ) {
2535 foreach my $index ( keys %{ $result{$key} } ) {
2536 $sth->execute( $result{$key}->{$index}, $server, $key, $index );
2539 $dbh->do('UNLOCK TABLES');
2543 # we use zebra, just fill zebraqueue table
2545 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2547 AND biblio_auth_number = ?
2550 my $check_sth = $dbh->prepare_cached($check_sql);
2551 $check_sth->execute( $server, $biblionumber, $op );
2552 my ($count) = $check_sth->fetchrow_array;
2553 $check_sth->finish();
2554 if ( $count == 0 ) {
2555 my $sth = $dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2556 $sth->execute( $biblionumber, $server, $op );
2562 =head2 GetNoZebraIndexes
2564 %indexes = GetNoZebraIndexes;
2566 return the data from NoZebraIndexes syspref.
2570 sub GetNoZebraIndexes {
2571 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2573 INDEX: foreach my $line ( split /['"],[\n\r]*/, $no_zebra_indexes ) {
2574 $line =~ /(.*)=>(.*)/;
2575 my $index = $1; # initial ' or " is removed afterwards
2577 $index =~ s/'|"|\s//g;
2578 $fields =~ s/'|"|\s//g;
2579 $indexes{$index} = $fields;
2584 =head2 EmbedItemsInMarcBiblio
2586 EmbedItemsInMarcBiblio($marc, $biblionumber);
2588 Given a MARC::Record object containing a bib record,
2589 modify it to include the items attached to it as 9XX
2590 per the bib's MARC framework.
2594 sub EmbedItemsInMarcBiblio {
2595 my ($marc, $biblionumber) = @_;
2596 croak "No MARC record" unless $marc;
2598 my $frameworkcode = GetFrameworkCode($biblionumber);
2599 _strip_item_fields($marc, $frameworkcode);
2601 # ... and embed the current items
2602 my $dbh = C4::Context->dbh;
2603 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
2604 $sth->execute($biblionumber);
2606 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2607 while (my ($itemnumber) = $sth->fetchrow_array) {
2609 my $item_marc = C4::Items::GetMarcItem($biblionumber, $itemnumber);
2610 push @item_fields, $item_marc->field($itemtag);
2612 $marc->append_fields(@item_fields);
2615 =head1 INTERNAL FUNCTIONS
2617 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2619 function to delete a biblio in NoZebra indexes
2620 This function does NOT delete anything in database : it reads all the indexes entries
2621 that have to be deleted & delete them in the hash
2623 The SQL part is done either :
2624 - after the Add if we are modifying a biblio (delete + add again)
2625 - immediatly after this sub if we are doing a true deletion.
2627 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2631 sub _DelBiblioNoZebra {
2632 my ( $biblionumber, $record, $server ) = @_;
2635 my $dbh = C4::Context->dbh;
2640 if ( $server eq 'biblioserver' ) {
2641 %index = GetNoZebraIndexes;
2643 # get title of the record (to store the 10 first letters with the index)
2644 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2645 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2648 # for authorities, the "title" is the $a mainentry
2649 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2650 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2651 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2652 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2653 $index{'mainmainentry'} = $authref->{'auth_tag_to_report'} . 'a';
2654 $index{'mainentry'} = $authref->{'auth_tag_to_report'} . '*';
2655 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2660 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2661 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2663 # limit to 10 char, should be enough, and limit the DB size
2664 $title = substr( $title, 0, 10 );
2667 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2668 foreach my $field ( $record->fields() ) {
2670 #parse each subfield
2671 next if $field->tag < 10;
2672 foreach my $subfield ( $field->subfields() ) {
2673 my $tag = $field->tag();
2674 my $subfieldcode = $subfield->[0];
2677 # check each index to see if the subfield is stored somewhere
2678 # otherwise, store it in __RAW__ index
2679 foreach my $key ( keys %index ) {
2681 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2682 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2684 my $line = lc $subfield->[1];
2686 # remove meaningless value in the field...
2687 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2689 # ... and split in words
2690 foreach ( split / /, $line ) {
2691 next unless $_; # skip empty values (multiple spaces)
2692 # if the entry is already here, do nothing, the biblionumber has already be removed
2693 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/ ) ) {
2695 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2696 $sth2->execute( $server, $key, $_ );
2697 my $existing_biblionumbers = $sth2->fetchrow;
2700 if ($existing_biblionumbers) {
2702 # warn " existing for $key $_: $existing_biblionumbers";
2703 $result{$key}->{$_} = $existing_biblionumbers;
2704 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2711 # the subfield is not indexed, store it in __RAW__ index anyway
2713 my $line = lc $subfield->[1];
2714 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2716 # ... and split in words
2717 foreach ( split / /, $line ) {
2718 next unless $_; # skip empty values (multiple spaces)
2719 # if the entry is already here, do nothing, the biblionumber has already be removed
2720 unless ( $result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/ ) {
2722 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2723 $sth2->execute( $server, '__RAW__', $_ );
2724 my $existing_biblionumbers = $sth2->fetchrow;
2727 if ($existing_biblionumbers) {
2728 $result{'__RAW__'}->{$_} = $existing_biblionumbers;
2729 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2739 =head2 _AddBiblioNoZebra
2741 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2743 function to add a biblio in NoZebra indexes
2747 sub _AddBiblioNoZebra {
2748 my ( $biblionumber, $record, $server, %result ) = @_;
2749 my $dbh = C4::Context->dbh;
2754 if ( $server eq 'biblioserver' ) {
2755 %index = GetNoZebraIndexes;
2757 # get title of the record (to store the 10 first letters with the index)
2758 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2759 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2762 # warn "server : $server";
2763 # for authorities, the "title" is the $a mainentry
2764 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2765 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2766 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2767 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2768 $index{'mainmainentry'} = $authref->{auth_tag_to_report} . 'a';
2769 $index{'mainentry'} = $authref->{auth_tag_to_report} . '*';
2770 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2773 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2774 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2776 # limit to 10 char, should be enough, and limit the DB size
2777 $title = substr( $title, 0, 10 );
2780 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2781 foreach my $field ( $record->fields() ) {
2783 #parse each subfield
2784 ###FIXME: impossible to index a 001-009 value with NoZebra
2785 next if $field->tag < 10;
2786 foreach my $subfield ( $field->subfields() ) {
2787 my $tag = $field->tag();
2788 my $subfieldcode = $subfield->[0];
2791 # warn "INDEXING :".$subfield->[1];
2792 # check each index to see if the subfield is stored somewhere
2793 # otherwise, store it in __RAW__ index
2794 foreach my $key ( keys %index ) {
2796 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2797 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2799 my $line = lc $subfield->[1];
2801 # remove meaningless value in the field...
2802 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2804 # ... and split in words
2805 foreach ( split / /, $line ) {
2806 next unless $_; # skip empty values (multiple spaces)
2807 # if the entry is already here, improve weight
2809 # warn "managing $_";
2810 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
2811 my $weight = $1 + 1;
2812 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2813 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2816 # get the value if it exist in the nozebra table, otherwise, create it
2817 $sth2->execute( $server, $key, $_ );
2818 my $existing_biblionumbers = $sth2->fetchrow;
2821 if ($existing_biblionumbers) {
2822 $result{$key}->{"$_"} = $existing_biblionumbers;
2823 my $weight = defined $1 ? $1 + 1 : 1;
2824 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2825 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2827 # create a new ligne for this entry
2830 # warn "INSERT : $server / $key / $_";
2831 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname=' . $dbh->quote($key) . ',value=' . $dbh->quote($_) );
2832 $result{$key}->{"$_"} .= "$biblionumber,$title-1;";
2839 # the subfield is not indexed, store it in __RAW__ index anyway
2841 my $line = lc $subfield->[1];
2842 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2844 # ... and split in words
2845 foreach ( split / /, $line ) {
2846 next unless $_; # skip empty values (multiple spaces)
2847 # if the entry is already here, improve weight
2848 my $tmpstr = $result{'__RAW__'}->{"$_"} || "";
2849 if ( $tmpstr =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
2850 my $weight = $1 + 1;
2851 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2852 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2855 # get the value if it exist in the nozebra table, otherwise, create it
2856 $sth2->execute( $server, '__RAW__', $_ );
2857 my $existing_biblionumbers = $sth2->fetchrow;
2860 if ($existing_biblionumbers) {
2861 $result{'__RAW__'}->{"$_"} = $existing_biblionumbers;
2862 my $weight = ( $1 ? $1 : 0 ) + 1;
2863 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2864 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2866 # create a new ligne for this entry
2868 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname="__RAW__",value=' . $dbh->quote($_) );
2869 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-1;";
2881 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2883 Find the given $subfield in the given $tag in the given
2884 MARC::Record $record. If the subfield is found, returns
2885 the (indicators, value) pair; otherwise, (undef, undef) is
2889 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2890 I suggest we export it from this module.
2895 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2898 if ( $tagfield < 10 ) {
2899 if ( $record->field($tagfield) ) {
2900 push @result, $record->field($tagfield)->data();
2905 foreach my $field ( $record->field($tagfield) ) {
2906 my @subfields = $field->subfields();
2907 foreach my $subfield (@subfields) {
2908 if ( @$subfield[0] eq $insubfield ) {
2909 push @result, @$subfield[1];
2910 $indicator = $field->indicator(1) . $field->indicator(2);
2915 return ( $indicator, @result );
2918 =head2 _koha_marc_update_bib_ids
2921 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2923 Internal function to add or update biblionumber and biblioitemnumber to
2928 sub _koha_marc_update_bib_ids {
2929 my ( $record, $frameworkcode, $biblionumber, $biblioitemnumber ) = @_;
2931 # we must add bibnum and bibitemnum in MARC::Record...
2932 # we build the new field with biblionumber and biblioitemnumber
2933 # we drop the original field
2934 # we add the new builded field.
2935 my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
2936 die qq{No biblionumber tag for framework "$frameworkcode"} unless $biblio_tag;
2937 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
2938 die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblio_tag;
2940 if ( $biblio_tag == $biblioitem_tag ) {
2942 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2943 my $new_field = MARC::Field->new(
2944 $biblio_tag, '', '',
2945 "$biblio_subfield" => $biblionumber,
2946 "$biblioitem_subfield" => $biblioitemnumber
2949 # drop old field and create new one...
2950 my $old_field = $record->field($biblio_tag);
2951 $record->delete_field($old_field) if $old_field;
2952 $record->insert_fields_ordered($new_field);
2955 # biblionumber & biblioitemnumber are in different fields
2957 # deal with biblionumber
2958 my ( $new_field, $old_field );
2959 if ( $biblio_tag < 10 ) {
2960 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2962 $new_field = MARC::Field->new( $biblio_tag, '', '', "$biblio_subfield" => $biblionumber );
2965 # drop old field and create new one...
2966 $old_field = $record->field($biblio_tag);
2967 $record->delete_field($old_field) if $old_field;
2968 $record->insert_fields_ordered($new_field);
2970 # deal with biblioitemnumber
2971 if ( $biblioitem_tag < 10 ) {
2972 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2974 $new_field = MARC::Field->new( $biblioitem_tag, '', '', "$biblioitem_subfield" => $biblioitemnumber, );
2977 # drop old field and create new one...
2978 $old_field = $record->field($biblioitem_tag);
2979 $record->delete_field($old_field) if $old_field;
2980 $record->insert_fields_ordered($new_field);
2984 =head2 _koha_marc_update_biblioitem_cn_sort
2986 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2988 Given a MARC bib record and the biblioitem hash, update the
2989 subfield that contains a copy of the value of biblioitems.cn_sort.
2993 sub _koha_marc_update_biblioitem_cn_sort {
2995 my $biblioitem = shift;
2996 my $frameworkcode = shift;
2998 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.cn_sort", $frameworkcode );
2999 return unless $biblioitem_tag;
3001 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3003 if ( my $field = $marc->field($biblioitem_tag) ) {
3004 $field->delete_subfield( code => $biblioitem_subfield );
3005 if ( $cn_sort ne '' ) {
3006 $field->add_subfields( $biblioitem_subfield => $cn_sort );
3010 # if we get here, no biblioitem tag is present in the MARC record, so
3011 # we'll create it if $cn_sort is not empty -- this would be
3012 # an odd combination of events, however
3014 $marc->insert_grouped_field( MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) );
3019 =head2 _koha_add_biblio
3021 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3023 Internal function to add a biblio ($biblio is a hash with the values)
3027 sub _koha_add_biblio {
3028 my ( $dbh, $biblio, $frameworkcode ) = @_;
3032 # set the series flag
3033 unless (defined $biblio->{'serial'}){
3034 $biblio->{'serial'} = 0;
3035 if ( $biblio->{'seriestitle'} ) { $biblio->{'serial'} = 1 }
3038 my $query = "INSERT INTO biblio
3039 SET frameworkcode = ?,
3050 my $sth = $dbh->prepare($query);
3052 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
3053 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}
3056 my $biblionumber = $dbh->{'mysql_insertid'};
3057 if ( $dbh->errstr ) {
3058 $error .= "ERROR in _koha_add_biblio $query" . $dbh->errstr;
3064 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3065 return ( $biblionumber, $error );
3068 =head2 _koha_modify_biblio
3070 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3072 Internal function for updating the biblio table
3076 sub _koha_modify_biblio {
3077 my ( $dbh, $biblio, $frameworkcode ) = @_;
3082 SET frameworkcode = ?,
3091 WHERE biblionumber = ?
3094 my $sth = $dbh->prepare($query);
3097 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
3098 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}, $biblio->{'biblionumber'}
3099 ) if $biblio->{'biblionumber'};
3101 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3102 $error .= "ERROR in _koha_modify_biblio $query" . $dbh->errstr;
3105 return ( $biblio->{'biblionumber'}, $error );
3108 =head2 _koha_modify_biblioitem_nonmarc
3110 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3112 Updates biblioitems row except for marc and marcxml, which should be changed
3117 sub _koha_modify_biblioitem_nonmarc {
3118 my ( $dbh, $biblioitem ) = @_;
3121 # re-calculate the cn_sort, it may have changed
3122 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3124 my $query = "UPDATE biblioitems
3125 SET biblionumber = ?,
3131 publicationyear = ?,
3135 collectiontitle = ?,
3137 collectionvolume= ?,
3138 editionstatement= ?,
3139 editionresponsibility = ?,
3153 where biblioitemnumber = ?
3155 my $sth = $dbh->prepare($query);
3157 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3158 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3159 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3160 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3161 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3162 $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'},
3163 $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'},
3164 $biblioitem->{'biblioitemnumber'}
3166 if ( $dbh->errstr ) {
3167 $error .= "ERROR in _koha_modify_biblioitem_nonmarc $query" . $dbh->errstr;
3170 return ( $biblioitem->{'biblioitemnumber'}, $error );
3173 =head2 _koha_add_biblioitem
3175 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3177 Internal function to add a biblioitem
3181 sub _koha_add_biblioitem {
3182 my ( $dbh, $biblioitem ) = @_;
3185 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3186 my $query = "INSERT INTO biblioitems SET
3193 publicationyear = ?,
3197 collectiontitle = ?,
3199 collectionvolume= ?,
3200 editionstatement= ?,
3201 editionresponsibility = ?,
3217 my $sth = $dbh->prepare($query);
3219 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3220 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3221 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3222 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3223 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3224 $biblioitem->{'lccn'}, $biblioitem->{'marc'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'},
3225 $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort,
3226 $biblioitem->{'totalissues'}
3228 my $bibitemnum = $dbh->{'mysql_insertid'};
3230 if ( $dbh->errstr ) {
3231 $error .= "ERROR in _koha_add_biblioitem $query" . $dbh->errstr;
3235 return ( $bibitemnum, $error );
3238 =head2 _koha_delete_biblio
3240 $error = _koha_delete_biblio($dbh,$biblionumber);
3242 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3244 C<$dbh> - the database handle
3246 C<$biblionumber> - the biblionumber of the biblio to be deleted
3250 # FIXME: add error handling
3252 sub _koha_delete_biblio {
3253 my ( $dbh, $biblionumber ) = @_;
3255 # get all the data for this biblio
3256 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3257 $sth->execute($biblionumber);
3259 if ( my $data = $sth->fetchrow_hashref ) {
3261 # save the record in deletedbiblio
3262 # find the fields to save
3263 my $query = "INSERT INTO deletedbiblio SET ";
3265 foreach my $temp ( keys %$data ) {
3266 $query .= "$temp = ?,";
3267 push( @bind, $data->{$temp} );
3270 # replace the last , by ",?)"
3272 my $bkup_sth = $dbh->prepare($query);
3273 $bkup_sth->execute(@bind);
3277 my $sth2 = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3278 $sth2->execute($biblionumber);
3279 # update the timestamp (Bugzilla 7146)
3280 $sth2= $dbh->prepare("UPDATE deletedbiblio SET timestamp=NOW() WHERE biblionumber=?");
3281 $sth2->execute($biblionumber);
3288 =head2 _koha_delete_biblioitems
3290 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3292 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3294 C<$dbh> - the database handle
3295 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3299 # FIXME: add error handling
3301 sub _koha_delete_biblioitems {
3302 my ( $dbh, $biblioitemnumber ) = @_;
3304 # get all the data for this biblioitem
3305 my $sth = $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3306 $sth->execute($biblioitemnumber);
3308 if ( my $data = $sth->fetchrow_hashref ) {
3310 # save the record in deletedbiblioitems
3311 # find the fields to save
3312 my $query = "INSERT INTO deletedbiblioitems SET ";
3314 foreach my $temp ( keys %$data ) {
3315 $query .= "$temp = ?,";
3316 push( @bind, $data->{$temp} );
3319 # replace the last , by ",?)"
3321 my $bkup_sth = $dbh->prepare($query);
3322 $bkup_sth->execute(@bind);
3325 # delete the biblioitem
3326 my $sth2 = $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3327 $sth2->execute($biblioitemnumber);
3328 # update the timestamp (Bugzilla 7146)
3329 $sth2= $dbh->prepare("UPDATE deletedbiblioitems SET timestamp=NOW() WHERE biblioitemnumber=?");
3330 $sth2->execute($biblioitemnumber);
3337 =head1 UNEXPORTED FUNCTIONS
3339 =head2 ModBiblioMarc
3341 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3343 Add MARC data for a biblio to koha
3345 Function exported, but should NOT be used, unless you really know what you're doing
3351 # pass the MARC::Record to this function, and it will create the records in the marc field
3352 my ( $record, $biblionumber, $frameworkcode ) = @_;
3353 my $dbh = C4::Context->dbh;
3354 my @fields = $record->fields();
3355 if ( !$frameworkcode ) {
3356 $frameworkcode = "";
3358 my $sth = $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3359 $sth->execute( $frameworkcode, $biblionumber );
3361 my $encoding = C4::Context->preference("marcflavour");
3363 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3364 if ( $encoding eq "UNIMARC" ) {
3365 my $string = $record->subfield( 100, "a" );
3366 if ( ($string) && ( length( $record->subfield( 100, "a" ) ) == 36 ) ) {
3367 my $f100 = $record->field(100);
3368 $record->delete_field($f100);
3370 $string = POSIX::strftime( "%Y%m%d", localtime );
3372 $string = sprintf( "%-*s", 35, $string );
3374 substr( $string, 22, 6, "frey50" );
3375 unless ( $record->subfield( 100, "a" ) ) {
3376 $record->insert_fields_ordered( MARC::Field->new( 100, "", "", "a" => $string ) );
3380 #enhancement 5374: update transaction date (005) for marc21/unimarc
3381 if($encoding =~ /MARC21|UNIMARC/) {
3382 my @a= (localtime) [5,4,3,2,1,0]; $a[0]+=1900; $a[1]++;
3383 # YY MM DD HH MM SS (update year and month)
3384 my $f005= $record->field('005');
3385 $f005->update(sprintf("%4d%02d%02d%02d%02d%04.1f",@a)) if $f005;
3389 if ( C4::Context->preference("NoZebra") ) {
3391 # only NoZebra indexing needs to have
3392 # the previous version of the record
3393 $oldRecord = GetMarcBiblio($biblionumber);
3395 $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3396 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding), $biblionumber );
3398 ModZebra( $biblionumber, "specialUpdate", "biblioserver", $oldRecord, $record );
3399 return $biblionumber;
3402 =head2 get_biblio_authorised_values
3404 find the types and values for all authorised values assigned to this biblio.
3408 MARC::Record of the bib
3410 returns: a hashref mapping the authorised value to the value set for this biblionumber
3412 $authorised_values = {
3413 'Scent' => 'flowery',
3414 'Audience' => 'Young Adult',
3415 'itemtypes' => 'SER',
3418 Notes: forlibrarian should probably be passed in, and called something different.
3422 sub get_biblio_authorised_values {
3423 my $biblionumber = shift;
3426 my $forlibrarian = 1; # are we in staff or opac?
3427 my $frameworkcode = GetFrameworkCode($biblionumber);
3429 my $authorised_values;
3431 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3432 or return $authorised_values;
3434 # assume that these entries in the authorised_value table are bibliolevel.
3435 # ones that start with 'item%' are item level.
3436 my $query = q(SELECT distinct authorised_value, kohafield
3437 FROM marc_subfield_structure
3438 WHERE authorised_value !=''
3439 AND (kohafield like 'biblio%'
3440 OR kohafield like '') );
3441 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3443 foreach my $tag ( keys(%$tagslib) ) {
3444 foreach my $subfield ( keys( %{ $tagslib->{$tag} } ) ) {
3446 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3447 if ( 'HASH' eq ref $tagslib->{$tag}{$subfield} ) {
3448 if ( defined $tagslib->{$tag}{$subfield}{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } ) {
3449 if ( defined $record->field($tag) ) {
3450 my $this_subfield_value = $record->field($tag)->subfield($subfield);
3451 if ( defined $this_subfield_value ) {
3452 $authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } = $this_subfield_value;
3460 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3461 return $authorised_values;
3464 =head2 CountBiblioInOrders
3467 $count = &CountBiblioInOrders( $biblionumber);
3471 This function return count of biblios in orders with $biblionumber
3475 sub CountBiblioInOrders {
3476 my ($biblionumber) = @_;
3477 my $dbh = C4::Context->dbh;
3478 my $query = "SELECT count(*)
3480 WHERE biblionumber=? AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')";
3481 my $sth = $dbh->prepare($query);
3482 $sth->execute($biblionumber);
3483 my $count = $sth->fetchrow;
3487 =head2 GetSubscriptionsId
3490 $subscriptions = &GetSubscriptionsId($biblionumber);
3494 This function return an array of subscriptionid with $biblionumber
3498 sub GetSubscriptionsId {
3499 my ($biblionumber) = @_;
3500 my $dbh = C4::Context->dbh;
3501 my $query = "SELECT subscriptionid
3503 WHERE biblionumber=?";
3504 my $sth = $dbh->prepare($query);
3505 $sth->execute($biblionumber);
3506 my @subscriptions = $sth->fetchrow_array;
3507 return (@subscriptions);
3513 $holds = &GetHolds($biblionumber);
3517 This function return the count of holds with $biblionumber
3522 my ($biblionumber) = @_;
3523 my $dbh = C4::Context->dbh;
3524 my $query = "SELECT count(*)
3526 WHERE biblionumber=?";
3527 my $sth = $dbh->prepare($query);
3528 $sth->execute($biblionumber);
3529 my $holds = $sth->fetchrow;
3540 Koha Development Team <http://koha-community.org/>
3542 Paul POULAIN paul.poulain@free.fr
3544 Joshua Ferraro jmf@liblime.com