3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2010 BibLibre
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 use MARC::File::USMARC;
29 use POSIX qw(strftime);
32 use C4::Dates qw/format_date/;
33 use C4::Log; # logaction
39 use vars qw($VERSION @ISA @EXPORT);
45 @ISA = qw( Exporter );
60 &GetBiblioItemByBiblioNumber
61 &GetBiblioFromItemNumber
62 &GetBiblionumberFromItemnumber
83 &GetAuthorisedValueDesc
104 # To link headings in a bib record
105 # to authority records.
107 &LinkBibHeadingsToAuthorities
111 # those functions are exported but should not be used
112 # they are usefull is few circumstances, so are exported.
113 # but don't use them unless you're a core developer ;-)
121 &TransformHtmlToMarc2
124 &PrepareItemrecordDisplay
130 my $servers = C4::Context->config('memcached_servers');
132 require Memoize::Memcached;
133 import Memoize::Memcached qw(memoize_memcached);
136 servers => [$servers],
137 key_prefix => C4::Context->config('memcached_namespace') || 'koha',
139 memoize_memcached( 'GetMarcStructure', memcached => $memcached, expire_time => 600 ); #cache for 10 minutes
145 C4::Biblio - cataloging management functions
149 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:
153 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
155 =item 2. as raw MARC in the Zebra index and storage engine
157 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
161 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
163 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.
167 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
169 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
173 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:
177 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
179 =item 2. _koha_* - low-level internal functions for managing the koha tables
181 =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.
183 =item 4. Zebra functions used to update the Zebra index
185 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
189 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 :
193 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
195 =item 2. add the biblionumber and biblioitemnumber into the MARC records
197 =item 3. save the marc record
201 When dealing with items, we must :
205 =item 1. save the item in items table, that gives us an itemnumber
207 =item 2. add the itemnumber to the item MARC field
209 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
211 When modifying a biblio or an item, the behaviour is quite similar.
215 =head1 EXPORTED FUNCTIONS
219 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
221 Exported function (core API) for adding a new biblio to koha.
223 The first argument is a C<MARC::Record> object containing the
224 bib to add, while the second argument is the desired MARC
227 This function also accepts a third, optional argument: a hashref
228 to additional options. The only defined option is C<defer_marc_save>,
229 which if present and mapped to a true value, causes C<AddBiblio>
230 to omit the call to save the MARC in C<bibilioitems.marc>
231 and C<biblioitems.marcxml> This option is provided B<only>
232 for the use of scripts such as C<bulkmarcimport.pl> that may need
233 to do some manipulation of the MARC record for item parsing before
234 saving it and which cannot afford the performance hit of saving
235 the MARC record twice. Consequently, do not use that option
236 unless you can guarantee that C<ModBiblioMarc> will be called.
242 my $frameworkcode = shift;
243 my $options = @_ ? shift : undef;
244 my $defer_marc_save = 0;
245 if ( defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'} ) {
246 $defer_marc_save = 1;
249 my ( $biblionumber, $biblioitemnumber, $error );
250 my $dbh = C4::Context->dbh;
252 # transform the data into koha-table style data
253 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
254 ( $biblionumber, $error ) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
255 $olddata->{'biblionumber'} = $biblionumber;
256 ( $biblioitemnumber, $error ) = _koha_add_biblioitem( $dbh, $olddata );
258 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
260 # update MARC subfield that stores biblioitems.cn_sort
261 _koha_marc_update_biblioitem_cn_sort( $record, $olddata, $frameworkcode );
264 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
266 logaction( "CATALOGUING", "ADD", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
267 return ( $biblionumber, $biblioitemnumber );
272 ModBiblio( $record,$biblionumber,$frameworkcode);
274 Replace an existing bib record identified by C<$biblionumber>
275 with one supplied by the MARC::Record object C<$record>. The embedded
276 item, biblioitem, and biblionumber fields from the previous
277 version of the bib record replace any such fields of those tags that
278 are present in C<$record>. Consequently, ModBiblio() is not
279 to be used to try to modify item records.
281 C<$frameworkcode> specifies the MARC framework to use
282 when storing the modified bib record; among other things,
283 this controls how MARC fields get mapped to display columns
284 in the C<biblio> and C<biblioitems> tables, as well as
285 which fields are used to store embedded item, biblioitem,
286 and biblionumber data for indexing.
291 my ( $record, $biblionumber, $frameworkcode ) = @_;
292 if ( C4::Context->preference("CataloguingLog") ) {
293 my $newrecord = GetMarcBiblio($biblionumber);
294 logaction( "CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>" . $newrecord->as_formatted );
297 my $dbh = C4::Context->dbh;
299 $frameworkcode = "" unless $frameworkcode;
301 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
302 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
303 my $oldRecord = GetMarcBiblio($biblionumber);
305 # delete any item fields from incoming record to avoid
306 # duplication or incorrect data - use AddItem() or ModItem()
308 foreach my $field ( $record->field($itemtag) ) {
309 $record->delete_field($field);
312 # parse each item, and, for an unknown reason, re-encode each subfield
313 # if you don't do that, the record will have encoding mixed
314 # and the biblio will be re-encoded.
315 # strange, I (Paul P.) searched more than 1 day to understand what happends
316 # but could only solve the problem this way...
317 my @fields = $oldRecord->field($itemtag);
318 foreach my $fielditem (@fields) {
320 foreach ( $fielditem->subfields() ) {
322 $field->add_subfields( Encode::encode( 'utf-8', $_->[0] ) => Encode::encode( 'utf-8', $_->[1] ) );
324 $field = MARC::Field->new( "$itemtag", '', '', Encode::encode( 'utf-8', $_->[0] ) => Encode::encode( 'utf-8', $_->[1] ) );
327 $record->append_fields($field);
330 foreach my $field ($record->fields()) {
331 if (! $field->is_control_field()) {
332 if (scalar($field->subfields()) == 0) {
333 $record->delete_fields($field);
338 # update biblionumber and biblioitemnumber in MARC
339 # FIXME - this is assuming a 1 to 1 relationship between
340 # biblios and biblioitems
341 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
342 $sth->execute($biblionumber);
343 my ($biblioitemnumber) = $sth->fetchrow;
345 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
347 # load the koha-table data object
348 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
350 # update MARC subfield that stores biblioitems.cn_sort
351 _koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode );
353 # update the MARC record (that now contains biblio and items) with the new record data
354 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
356 # modify the other koha tables
357 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
358 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
362 =head2 ModBiblioframework
364 ModBiblioframework($biblionumber,$frameworkcode);
366 Exported function to modify a biblio framework
370 sub ModBiblioframework {
371 my ( $biblionumber, $frameworkcode ) = @_;
372 my $dbh = C4::Context->dbh;
373 my $sth = $dbh->prepare( "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?" );
374 $sth->execute( $frameworkcode, $biblionumber );
380 my $error = &DelBiblio($dbh,$biblionumber);
382 Exported function (core API) for deleting a biblio in koha.
383 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
384 Also backs it up to deleted* tables
385 Checks to make sure there are not issues on any of the items
387 C<$error> : undef unless an error occurs
392 my ($biblionumber) = @_;
393 my $dbh = C4::Context->dbh;
394 my $error; # for error handling
396 # First make sure this biblio has no items attached
397 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
398 $sth->execute($biblionumber);
399 if ( my $itemnumber = $sth->fetchrow ) {
401 # Fix this to use a status the template can understand
402 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
405 return $error if $error;
407 # We delete attached subscriptions
408 my $subscriptions = &C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
409 foreach my $subscription (@$subscriptions) {
410 &C4::Serials::DelSubscription( $subscription->{subscriptionid} );
413 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
414 # for at least 2 reasons :
415 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
416 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
417 # 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)
419 if ( C4::Context->preference("NoZebra") ) {
421 # only NoZebra indexing needs to have
422 # the previous version of the record
423 $oldRecord = GetMarcBiblio($biblionumber);
425 ModZebra( $biblionumber, "recordDelete", "biblioserver", $oldRecord, undef );
427 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
428 $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
429 $sth->execute($biblionumber);
430 while ( my $biblioitemnumber = $sth->fetchrow ) {
432 # delete this biblioitem
433 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
434 return $error if $error;
437 # delete biblio from Koha tables and save in deletedbiblio
438 # must do this *after* _koha_delete_biblioitems, otherwise
439 # delete cascade will prevent deletedbiblioitems rows
440 # from being generated by _koha_delete_biblioitems
441 $error = _koha_delete_biblio( $dbh, $biblionumber );
443 logaction( "CATALOGUING", "DELETE", $biblionumber, "" ) if C4::Context->preference("CataloguingLog");
448 =head2 LinkBibHeadingsToAuthorities
450 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
452 Links bib headings to authority records by checking
453 each authority-controlled field in the C<MARC::Record>
454 object C<$marc>, looking for a matching authority record,
455 and setting the linking subfield $9 to the ID of that
458 If no matching authority exists, or if multiple
459 authorities match, no $9 will be added, and any
460 existing one inthe field will be deleted.
462 Returns the number of heading links changed in the
467 sub LinkBibHeadingsToAuthorities {
470 my $num_headings_changed = 0;
471 foreach my $field ( $bib->fields() ) {
472 my $heading = C4::Heading->new_from_bib_field($field);
473 next unless defined $heading;
476 my $current_link = $field->subfield('9');
478 # look for matching authorities
479 my $authorities = $heading->authorities();
481 # want only one exact match
482 if ( $#{$authorities} == 0 ) {
483 my $authority = MARC::Record->new_from_usmarc( $authorities->[0] );
484 my $authid = $authority->field('001')->data();
485 next if defined $current_link and $current_link eq $authid;
487 $field->delete_subfield( code => '9' ) if defined $current_link;
488 $field->add_subfields( '9', $authid );
489 $num_headings_changed++;
491 if ( defined $current_link ) {
492 $field->delete_subfield( code => '9' );
493 $num_headings_changed++;
498 return $num_headings_changed;
501 =head2 GetRecordValue
503 my $values = GetRecordValue($field, $record, $frameworkcode);
505 Get MARC fields from a keyword defined in fieldmapping table.
510 my ( $field, $record, $frameworkcode ) = @_;
511 my $dbh = C4::Context->dbh;
513 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
514 $sth->execute( $frameworkcode, $field );
518 while ( my $row = $sth->fetchrow_hashref ) {
519 foreach my $field ( $record->field( $row->{fieldcode} ) ) {
520 if ( ( $row->{subfieldcode} ne "" && $field->subfield( $row->{subfieldcode} ) ) ) {
521 foreach my $subfield ( $field->subfield( $row->{subfieldcode} ) ) {
522 push @result, { 'subfield' => $subfield };
525 } elsif ( $row->{subfieldcode} eq "" ) {
526 push @result, { 'subfield' => $field->as_string() };
534 =head2 SetFieldMapping
536 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
538 Set a Field to MARC mapping value, if it already exists we don't add a new one.
542 sub SetFieldMapping {
543 my ( $framework, $field, $fieldcode, $subfieldcode ) = @_;
544 my $dbh = C4::Context->dbh;
546 my $sth = $dbh->prepare('SELECT * FROM fieldmapping WHERE fieldcode = ? AND subfieldcode = ? AND frameworkcode = ? AND field = ?');
547 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
548 if ( not $sth->fetchrow_hashref ) {
550 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
552 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
556 =head2 DeleteFieldMapping
558 DeleteFieldMapping($id);
560 Delete a field mapping from an $id.
564 sub DeleteFieldMapping {
566 my $dbh = C4::Context->dbh;
568 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
572 =head2 GetFieldMapping
574 GetFieldMapping($frameworkcode);
576 Get all field mappings for a specified frameworkcode
580 sub GetFieldMapping {
581 my ($framework) = @_;
582 my $dbh = C4::Context->dbh;
584 my $sth = $dbh->prepare('SELECT * FROM fieldmapping where frameworkcode = ?');
585 $sth->execute($framework);
588 while ( my $row = $sth->fetchrow_hashref ) {
596 $data = &GetBiblioData($biblionumber);
598 Returns information about the book with the given biblionumber.
599 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
600 the C<biblio> and C<biblioitems> tables in the
603 In addition, C<$data-E<gt>{subject}> is the list of the book's
604 subjects, separated by C<" , "> (space, comma, space).
605 If there are multiple biblioitems with the given biblionumber, only
606 the first one is considered.
612 my $dbh = C4::Context->dbh;
614 # my $query = C4::Context->preference('item-level_itypes') ?
615 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
617 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
618 # WHERE biblio.biblionumber = ?
619 # AND biblioitems.biblionumber = biblio.biblionumber
622 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
624 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
625 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
626 WHERE biblio.biblionumber = ?
627 AND biblioitems.biblionumber = biblio.biblionumber ";
629 my $sth = $dbh->prepare($query);
630 $sth->execute($bibnum);
632 $data = $sth->fetchrow_hashref;
636 } # sub GetBiblioData
638 =head2 &GetBiblioItemData
640 $itemdata = &GetBiblioItemData($biblioitemnumber);
642 Looks up the biblioitem with the given biblioitemnumber. Returns a
643 reference-to-hash. The keys are the fields from the C<biblio>,
644 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
645 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
650 sub GetBiblioItemData {
651 my ($biblioitemnumber) = @_;
652 my $dbh = C4::Context->dbh;
653 my $query = "SELECT *,biblioitems.notes AS bnotes
654 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
655 unless ( C4::Context->preference('item-level_itypes') ) {
656 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
658 $query .= " WHERE biblioitemnumber = ? ";
659 my $sth = $dbh->prepare($query);
661 $sth->execute($biblioitemnumber);
662 $data = $sth->fetchrow_hashref;
665 } # sub &GetBiblioItemData
667 =head2 GetBiblioItemByBiblioNumber
669 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
673 sub GetBiblioItemByBiblioNumber {
674 my ($biblionumber) = @_;
675 my $dbh = C4::Context->dbh;
676 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
680 $sth->execute($biblionumber);
682 while ( my $data = $sth->fetchrow_hashref ) {
683 push @results, $data;
690 =head2 GetBiblionumberFromItemnumber
695 sub GetBiblionumberFromItemnumber {
696 my ($itemnumber) = @_;
697 my $dbh = C4::Context->dbh;
698 my $sth = $dbh->prepare("Select biblionumber FROM items WHERE itemnumber = ?");
700 $sth->execute($itemnumber);
701 my ($result) = $sth->fetchrow;
705 =head2 GetBiblioFromItemNumber
707 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
709 Looks up the item with the given itemnumber. if undef, try the barcode.
711 C<&itemnodata> returns a reference-to-hash whose keys are the fields
712 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
718 sub GetBiblioFromItemNumber {
719 my ( $itemnumber, $barcode ) = @_;
720 my $dbh = C4::Context->dbh;
723 $sth = $dbh->prepare(
725 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
726 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
727 WHERE items.itemnumber = ?"
729 $sth->execute($itemnumber);
731 $sth = $dbh->prepare(
733 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
734 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
735 WHERE items.barcode = ?"
737 $sth->execute($barcode);
739 my $data = $sth->fetchrow_hashref;
746 $isbd = &GetISBDView($biblionumber);
748 Return the ISBD view which can be included in opac and intranet
753 my ( $biblionumber, $template ) = @_;
754 my $record = GetMarcBiblio($biblionumber);
755 my $itemtype = &GetFrameworkCode($biblionumber);
756 my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch", $itemtype );
757 my $tagslib = &GetMarcStructure( 1, $itemtype );
759 my $ISBD = C4::Context->preference('isbd');
764 foreach my $isbdfield ( split( /#/, $bloc ) ) {
766 # $isbdfield= /(.?.?.?)/;
767 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
768 my $fieldvalue = $1 || 0;
769 my $subfvalue = $2 || "";
771 my $analysestring = $4;
774 # warn "==> $1 / $2 / $3 / $4";
775 # my $fieldvalue=substr($isbdfield,0,3);
776 if ( $fieldvalue > 0 ) {
777 my $hasputtextbefore = 0;
778 my @fieldslist = $record->field($fieldvalue);
779 @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf );
781 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
782 # warn "FV : $fieldvalue";
783 if ( $subfvalue ne "" ) {
784 foreach my $field (@fieldslist) {
785 foreach my $subfield ( $field->subfield($subfvalue) ) {
786 my $calculated = $analysestring;
787 my $tag = $field->tag();
790 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib );
791 my $tagsubf = $tag . $subfvalue;
792 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
793 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
795 # field builded, store the result
796 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
797 $blocres .= $textbefore;
798 $hasputtextbefore = 1;
801 # remove punctuation at start
802 $calculated =~ s/^( |;|:|\.|-)*//g;
803 $blocres .= $calculated;
808 $blocres .= $textafter if $hasputtextbefore;
810 foreach my $field (@fieldslist) {
811 my $calculated = $analysestring;
812 my $tag = $field->tag();
815 my @subf = $field->subfields;
816 for my $i ( 0 .. $#subf ) {
817 my $valuecode = $subf[$i][1];
818 my $subfieldcode = $subf[$i][0];
819 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib );
820 my $tagsubf = $tag . $subfieldcode;
822 $calculated =~ s/ # replace all {{}} codes by the value code.
823 \{\{$tagsubf\}\} # catch the {{actualcode}}
825 $valuecode # replace by the value code
828 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
829 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
832 # field builded, store the result
833 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
834 $blocres .= $textbefore;
835 $hasputtextbefore = 1;
838 # remove punctuation at start
839 $calculated =~ s/^( |;|:|\.|-)*//g;
840 $blocres .= $calculated;
843 $blocres .= $textafter if $hasputtextbefore;
846 $blocres .= $isbdfield;
851 $res =~ s/\{(.*?)\}//g;
853 $res =~ s/\n/<br\/>/g;
863 ( $count, @results ) = &GetBiblio($biblionumber);
868 my ($biblionumber) = @_;
869 my $dbh = C4::Context->dbh;
870 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
873 $sth->execute($biblionumber);
874 while ( my $data = $sth->fetchrow_hashref ) {
875 $results[$count] = $data;
879 return ( $count, @results );
882 =head2 GetBiblioItemInfosOf
884 GetBiblioItemInfosOf(@biblioitemnumbers);
888 sub GetBiblioItemInfosOf {
889 my @biblioitemnumbers = @_;
892 SELECT biblioitemnumber,
896 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
898 return get_infos_of( $query, 'biblioitemnumber' );
901 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
903 =head2 GetMarcStructure
905 $res = GetMarcStructure($forlibrarian,$frameworkcode);
907 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
908 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
909 $frameworkcode : the framework code to read
913 # cache for results of GetMarcStructure -- needed
915 our $marc_structure_cache;
917 sub GetMarcStructure {
918 my ( $forlibrarian, $frameworkcode ) = @_;
919 my $dbh = C4::Context->dbh;
920 $frameworkcode = "" unless $frameworkcode;
922 if ( defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode} ) {
923 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
926 # my $sth = $dbh->prepare(
927 # "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
928 # $sth->execute($frameworkcode);
929 # my ($total) = $sth->fetchrow;
930 # $frameworkcode = "" unless ( $total > 0 );
931 my $sth = $dbh->prepare(
932 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
933 FROM marc_tag_structure
934 WHERE frameworkcode=?
937 $sth->execute($frameworkcode);
938 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
940 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
941 $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
942 $res->{$tag}->{tab} = "";
943 $res->{$tag}->{mandatory} = $mandatory;
944 $res->{$tag}->{repeatable} = $repeatable;
947 $sth = $dbh->prepare(
948 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
949 FROM marc_subfield_structure
950 WHERE frameworkcode=?
951 ORDER BY tagfield,tagsubfield
955 $sth->execute($frameworkcode);
958 my $authorised_value;
969 ( $tag, $subfield, $liblibrarian, $libopac, $tab, $mandatory, $repeatable, $authorised_value,
970 $authtypecode, $value_builder, $kohafield, $seealso, $hidden, $isurl, $link, $defaultvalue
974 $res->{$tag}->{$subfield}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
975 $res->{$tag}->{$subfield}->{tab} = $tab;
976 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
977 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
978 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
979 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
980 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
981 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
982 $res->{$tag}->{$subfield}->{seealso} = $seealso;
983 $res->{$tag}->{$subfield}->{hidden} = $hidden;
984 $res->{$tag}->{$subfield}->{isurl} = $isurl;
985 $res->{$tag}->{$subfield}->{'link'} = $link;
986 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
989 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
994 =head2 GetUsedMarcStructure
996 The same function as GetMarcStructure except it just takes field
997 in tab 0-9. (used field)
999 my $results = GetUsedMarcStructure($frameworkcode);
1001 C<$results> is a ref to an array which each case containts a ref
1002 to a hash which each keys is the columns from marc_subfield_structure
1004 C<$frameworkcode> is the framework code.
1008 sub GetUsedMarcStructure($) {
1009 my $frameworkcode = shift || '';
1012 FROM marc_subfield_structure
1014 AND frameworkcode = ?
1015 ORDER BY tagfield, tagsubfield
1017 my $sth = C4::Context->dbh->prepare($query);
1018 $sth->execute($frameworkcode);
1019 return $sth->fetchall_arrayref( {} );
1022 =head2 GetMarcFromKohaField
1024 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1026 Returns the MARC fields & subfields mapped to the koha field
1027 for the given frameworkcode
1031 sub GetMarcFromKohaField {
1032 my ( $kohafield, $frameworkcode ) = @_;
1033 return 0, 0 unless $kohafield and defined $frameworkcode;
1034 my $relations = C4::Context->marcfromkohafield;
1035 return ( $relations->{$frameworkcode}->{$kohafield}->[0], $relations->{$frameworkcode}->{$kohafield}->[1] );
1038 =head2 GetMarcBiblio
1040 my $record = GetMarcBiblio($biblionumber);
1042 Returns MARC::Record representing bib identified by
1043 C<$biblionumber>. If no bib exists, returns undef.
1044 The MARC record contains both biblio & item data.
1049 my $biblionumber = shift;
1050 my $dbh = C4::Context->dbh;
1051 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1052 $sth->execute($biblionumber);
1053 my $row = $sth->fetchrow_hashref;
1054 my $marcxml = StripNonXmlChars( $row->{'marcxml'} );
1055 MARC::File::XML->default_record_format( C4::Context->preference('marcflavour') );
1056 my $record = MARC::Record->new();
1059 $record = eval { MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour') ) };
1060 if ($@) { warn " problem with :$biblionumber : $@ \n$marcxml"; }
1062 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1071 my $marcxml = GetXmlBiblio($biblionumber);
1073 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1074 The XML contains both biblio & item datas
1079 my ($biblionumber) = @_;
1080 my $dbh = C4::Context->dbh;
1081 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1082 $sth->execute($biblionumber);
1083 my ($marcxml) = $sth->fetchrow;
1087 =head2 GetCOinSBiblio
1089 my $coins = GetCOinSBiblio($biblionumber);
1091 Returns the COinS(a span) which can be included in a biblio record
1095 sub GetCOinSBiblio {
1096 my ($biblionumber) = @_;
1097 my $record = GetMarcBiblio($biblionumber);
1099 # get the coin format
1101 # can't get a valid MARC::Record object, bail out at this point
1102 warn "We called GetMarcBiblio with a biblionumber that doesn't exist biblionumber=$biblionumber";
1105 my $pos7 = substr $record->leader(), 7, 1;
1106 my $pos6 = substr $record->leader(), 6, 1;
1109 my ( $aulast, $aufirst ) = ( '', '' );
1118 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
1123 'b' => 'manuscript',
1125 'd' => 'manuscript',
1129 'i' => 'audioRecording',
1130 'j' => 'audioRecording',
1133 'm' => 'computerProgram',
1138 'a' => 'journalArticle',
1142 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
1144 if ( $genre eq 'book' ) {
1145 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1148 ##### We must transform mtx to a valable mtx and document type ####
1149 if ( $genre eq 'book' ) {
1151 } elsif ( $genre eq 'journal' ) {
1153 } elsif ( $genre eq 'journalArticle' ) {
1160 $genre = ( $mtx eq 'dc' ) ? "&rft.type=$genre" : "&rft.genre=$genre";
1163 $aulast = $record->subfield( '700', 'a' );
1164 $aufirst = $record->subfield( '700', 'b' );
1165 $oauthors = "&rft.au=$aufirst $aulast";
1168 if ( $record->field('200') ) {
1169 for my $au ( $record->field('200')->subfield('g') ) {
1170 $oauthors .= "&rft.au=$au";
1175 ? "&rft.title=" . $record->subfield( '200', 'a' )
1176 : "&rft.title=" . $record->subfield( '200', 'a' ) . "&rft.btitle=" . $record->subfield( '200', 'a' );
1177 $pubyear = $record->subfield( '210', 'd' );
1178 $publisher = $record->subfield( '210', 'c' );
1179 $isbn = $record->subfield( '010', 'a' );
1180 $issn = $record->subfield( '011', 'a' );
1183 # MARC21 need some improve
1186 $genre = "&rft.genre=book";
1189 if ( $record->field('100') ) {
1190 $oauthors .= "&rft.au=" . $record->subfield( '100', 'a' );
1194 if ( $record->field('700') ) {
1195 for my $au ( $record->field('700')->subfield('a') ) {
1196 $oauthors .= "&rft.au=$au";
1199 $title = "&rft.btitle=" . $record->subfield( '245', 'a' );
1200 $subtitle = $record->subfield( '245', 'b' ) || '';
1201 $title .= $subtitle;
1202 $pubyear = $record->subfield( '260', 'c' ) || '';
1203 $publisher = $record->subfield( '260', 'b' ) || '';
1204 $isbn = $record->subfield( '020', 'a' ) || '';
1205 $issn = $record->subfield( '022', 'a' ) || '';
1209 "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";
1210 $coins_value =~ s/(\ |&[^a])/\+/g;
1211 $coins_value =~ s/\"/\"\;/g;
1213 #<!-- 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="
1215 return $coins_value;
1218 =head2 GetAuthorisedValueDesc
1220 my $subfieldvalue =get_authorised_value_desc(
1221 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category, $opac);
1223 Retrieve the complete description for a given authorised value.
1225 Now takes $category and $value pair too.
1227 my $auth_value_desc =GetAuthorisedValueDesc(
1228 '','', 'DVD' ,'','','CCODE');
1230 If the optional $opac parameter is set to a true value, displays OPAC
1231 descriptions rather than normal ones when they exist.
1235 sub GetAuthorisedValueDesc {
1236 my ( $tag, $subfield, $value, $framework, $tagslib, $category, $opac ) = @_;
1237 my $dbh = C4::Context->dbh;
1241 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1244 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1245 return C4::Branch::GetBranchName($value);
1249 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1250 return getitemtypeinfo($value)->{description};
1253 #---- "true" authorized value
1254 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1257 if ( $category ne "" ) {
1258 my $sth = $dbh->prepare( "SELECT lib, lib_opac FROM authorised_values WHERE category = ? AND authorised_value = ?" );
1259 $sth->execute( $category, $value );
1260 my $data = $sth->fetchrow_hashref;
1261 return ( $opac && $data->{'lib_opac'} ) ? $data->{'lib_opac'} : $data->{'lib'};
1263 return $value; # if nothing is found return the original value
1267 =head2 GetMarcControlnumber
1269 $marccontrolnumber = GetMarcControlnumber($record,$marcflavour);
1271 Get the control number / record Identifier from the MARC record and return it.
1275 sub GetMarcControlnumber {
1276 my ( $record, $marcflavour ) = @_;
1277 my $controlnumber = "";
1278 # Control number or Record identifier are the same field in MARC21 and UNIMARC
1279 # Keep $marcflavour for possible later use
1280 if ($marcflavour eq "MARC21" || $marcflavour eq "UNIMARC") {
1281 my $controlnumberField = $record->field('001');
1282 if ($controlnumberField) {
1283 $controlnumber = $controlnumberField->data();
1286 return $controlnumber;
1291 $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
1293 Get all ISBNs from the MARC record and returns them in an array.
1294 ISBNs stored in differents places depending on MARC flavour
1299 my ( $record, $marcflavour ) = @_;
1301 if ( $marcflavour eq "MARC21" ) {
1303 } else { # assume unimarc if not marc21
1310 foreach my $field ( $record->field($scope) ) {
1311 my $value = $field->as_string();
1312 if ( $isbn ne "" ) {
1313 $marcisbn = { marcisbn => $isbn, };
1314 push @marcisbns, $marcisbn;
1317 if ( $isbn ne $value ) {
1318 $isbn = $isbn . " " . $value;
1323 $marcisbn = { marcisbn => $isbn };
1324 push @marcisbns, $marcisbn; #load last tag into array
1331 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1333 Get all notes from the MARC record and returns them in an array.
1334 The note are stored in differents places depending on MARC flavour
1339 my ( $record, $marcflavour ) = @_;
1341 if ( $marcflavour eq "MARC21" ) {
1343 } else { # assume unimarc if not marc21
1350 foreach my $field ( $record->field($scope) ) {
1351 my $value = $field->as_string();
1352 if ( $note ne "" ) {
1353 $marcnote = { marcnote => $note, };
1354 push @marcnotes, $marcnote;
1357 if ( $note ne $value ) {
1358 $note = $note . " " . $value;
1363 $marcnote = { marcnote => $note };
1364 push @marcnotes, $marcnote; #load last tag into array
1367 } # end GetMarcNotes
1369 =head2 GetMarcSubjects
1371 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1373 Get all subjects from the MARC record and returns them in an array.
1374 The subjects are stored in differents places depending on MARC flavour
1378 sub GetMarcSubjects {
1379 my ( $record, $marcflavour ) = @_;
1380 my ( $mintag, $maxtag );
1381 if ( $marcflavour eq "MARC21" ) {
1384 } else { # assume unimarc if not marc21
1394 my $subject_limit = C4::Context->preference("TraceCompleteSubfields") ? 'su,complete-subfield' : 'su';
1396 foreach my $field ( $record->field('6..') ) {
1397 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1399 my @subfields = $field->subfields();
1403 # if there is an authority link, build the link with an= subfield9
1405 for my $subject_subfield (@subfields) {
1407 # don't load unimarc subfields 3,4,5
1408 next if ( ( $marcflavour eq "UNIMARC" ) and ( $subject_subfield->[0] =~ /2|3|4|5/ ) );
1410 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1411 next if ( ( $marcflavour eq "MARC21" ) and ( $subject_subfield->[0] =~ /2/ ) );
1412 my $code = $subject_subfield->[0];
1413 my $value = $subject_subfield->[1];
1414 my $linkvalue = $value;
1415 $linkvalue =~ s/(\(|\))//g;
1416 my $operator = " and " unless $counter == 0;
1419 @link_loop = ( { 'limit' => 'an', link => "$linkvalue" } );
1421 if ( not $found9 ) {
1422 push @link_loop, { 'limit' => $subject_limit, link => $linkvalue, operator => $operator };
1424 my $separator = C4::Context->preference("authoritysep") unless $counter == 0;
1427 my @this_link_loop = @link_loop;
1428 push @subfields_loop, { code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator } unless ( $subject_subfield->[0] eq 9 );
1432 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1435 return \@marcsubjects;
1436 } #end getMARCsubjects
1438 =head2 GetMarcAuthors
1440 authors = GetMarcAuthors($record,$marcflavour);
1442 Get all authors from the MARC record and returns them in an array.
1443 The authors are stored in differents places depending on MARC flavour
1447 sub GetMarcAuthors {
1448 my ( $record, $marcflavour ) = @_;
1449 my ( $mintag, $maxtag );
1451 # tagslib useful for UNIMARC author reponsabilities
1453 &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.
1454 if ( $marcflavour eq "MARC21" ) {
1457 } elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1465 foreach my $field ( $record->fields ) {
1466 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1469 my @subfields = $field->subfields();
1472 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1473 my $subfield9 = $field->subfield('9');
1474 for my $authors_subfield (@subfields) {
1476 # don't load unimarc subfields 3, 5
1477 next if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /3|5/ ) );
1478 my $subfieldcode = $authors_subfield->[0];
1479 my $value = $authors_subfield->[1];
1480 my $linkvalue = $value;
1481 $linkvalue =~ s/(\(|\))//g;
1482 my $operator = " and " unless $count_auth == 0;
1484 # if we have an authority link, use that as the link, otherwise use standard searching
1486 @link_loop = ( { 'limit' => 'an', link => "$subfield9" } );
1489 # reset $linkvalue if UNIMARC author responsibility
1490 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] eq "4" ) ) {
1491 $linkvalue = "(" . GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) . ")";
1493 push @link_loop, { 'limit' => 'au', link => $linkvalue, operator => $operator };
1495 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib )
1496 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /4/ ) );
1497 my @this_link_loop = @link_loop;
1498 my $separator = C4::Context->preference("authoritysep") unless $count_auth == 0;
1499 push @subfields_loop, { code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator } unless ( $authors_subfield->[0] eq '9' );
1502 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1504 return \@marcauthors;
1509 $marcurls = GetMarcUrls($record,$marcflavour);
1511 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1512 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1517 my ( $record, $marcflavour ) = @_;
1520 for my $field ( $record->field('856') ) {
1522 for my $note ( $field->subfield('z') ) {
1523 push @notes, { note => $note };
1525 my @urls = $field->subfield('u');
1526 foreach my $url (@urls) {
1528 if ( $marcflavour eq 'MARC21' ) {
1529 my $s3 = $field->subfield('3');
1530 my $link = $field->subfield('y');
1531 unless ( $url =~ /^\w+:/ ) {
1532 if ( $field->indicator(1) eq '7' ) {
1533 $url = $field->subfield('2') . "://" . $url;
1534 } elsif ( $field->indicator(1) eq '1' ) {
1535 $url = 'ftp://' . $url;
1538 # properly, this should be if ind1=4,
1539 # however we will assume http protocol since we're building a link.
1540 $url = 'http://' . $url;
1544 # TODO handle ind 2 (relationship)
1549 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1550 $marcurl->{'part'} = $s3 if ($link);
1551 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1553 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1554 $marcurl->{'MARCURL'} = $url;
1556 push @marcurls, $marcurl;
1562 =head2 GetMarcSeries
1564 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1566 Get all series from the MARC record and returns them in an array.
1567 The series are stored in differents places depending on MARC flavour
1572 my ( $record, $marcflavour ) = @_;
1573 my ( $mintag, $maxtag );
1574 if ( $marcflavour eq "MARC21" ) {
1577 } else { # assume unimarc if not marc21
1587 foreach my $field ( $record->field('440'), $record->field('490') ) {
1590 #my $value = $field->subfield('a');
1591 #$marcsubjct = {MARCSUBJCT => $value,};
1592 my @subfields = $field->subfields();
1594 #warn "subfields:".join " ", @$subfields;
1597 for my $series_subfield (@subfields) {
1599 undef $volume_number;
1601 # see if this is an instance of a volume
1602 if ( $series_subfield->[0] eq 'v' ) {
1606 my $code = $series_subfield->[0];
1607 my $value = $series_subfield->[1];
1608 my $linkvalue = $value;
1609 $linkvalue =~ s/(\(|\))//g;
1610 my $operator = " and " unless $counter == 0;
1611 push @link_loop, { link => $linkvalue, operator => $operator };
1612 my $separator = C4::Context->preference("authoritysep") unless $counter == 0;
1613 if ($volume_number) {
1614 push @subfields_loop, { volumenum => $value };
1616 push @subfields_loop, { code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number } unless ( $series_subfield->[0] eq '9' );
1620 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1622 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1623 #push @marcsubjcts, $marcsubjct;
1627 my $marcseriessarray = \@marcseries;
1628 return $marcseriessarray;
1629 } #end getMARCseriess
1631 =head2 GetFrameworkCode
1633 $frameworkcode = GetFrameworkCode( $biblionumber )
1637 sub GetFrameworkCode {
1638 my ($biblionumber) = @_;
1639 my $dbh = C4::Context->dbh;
1640 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1641 $sth->execute($biblionumber);
1642 my ($frameworkcode) = $sth->fetchrow;
1643 return $frameworkcode;
1646 =head2 TransformKohaToMarc
1648 $record = TransformKohaToMarc( $hash )
1650 This function builds partial MARC::Record from a hash
1651 Hash entries can be from biblio or biblioitems.
1653 This function is called in acquisition module, to create a basic catalogue entry from user entry
1657 sub TransformKohaToMarc {
1659 my $sth = C4::Context->dbh->prepare( "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?" );
1660 my $record = MARC::Record->new();
1661 SetMarcUnicodeFlag( $record, C4::Context->preference("marcflavour") );
1662 foreach ( keys %{$hash} ) {
1663 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1668 =head2 TransformKohaToMarcOneField
1670 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1674 sub TransformKohaToMarcOneField {
1675 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1676 $frameworkcode = '' unless $frameworkcode;
1680 if ( !defined $sth ) {
1681 my $dbh = C4::Context->dbh;
1682 $sth = $dbh->prepare( "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?" );
1684 $sth->execute( $frameworkcode, $kohafieldname );
1685 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1686 my @values = split(/\s?\|\s?/, $value, -1);
1688 foreach my $itemvalue (@values){
1689 my $tag = $record->field($tagfield);
1691 $tag->add_subfields( $tagsubfield => $itemvalue );
1692 $record->delete_field($tag);
1693 $record->insert_fields_ordered($tag);
1696 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $itemvalue );
1703 =head2 TransformHtmlToXml
1705 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator,
1706 $ind_tag, $auth_type )
1708 $auth_type contains :
1712 =item - nothing : rebuild a biblio. In UNIMARC the encoding is in 100$a pos 26/27
1714 =item - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1716 =item - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1722 sub TransformHtmlToXml {
1723 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1724 my $xml = MARC::File::XML::header('UTF-8');
1725 $xml .= "<record>\n";
1726 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1727 MARC::File::XML->default_record_format($auth_type);
1729 # in UNIMARC, field 100 contains the encoding
1730 # check that there is one, otherwise the
1731 # MARC::Record->new_from_xml will fail (and Koha will die)
1732 my $unimarc_and_100_exist = 0;
1733 $unimarc_and_100_exist = 1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1738 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1740 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a" ) {
1742 # if we have a 100 field and it's values are not correct, skip them.
1743 # if we don't have any valid 100 field, we will create a default one at the end
1744 my $enc = substr( @$values[$i], 26, 2 );
1745 if ( $enc eq '01' or $enc eq '50' or $enc eq '03' ) {
1746 $unimarc_and_100_exist = 1;
1751 @$values[$i] =~ s/&/&/g;
1752 @$values[$i] =~ s/</</g;
1753 @$values[$i] =~ s/>/>/g;
1754 @$values[$i] =~ s/"/"/g;
1755 @$values[$i] =~ s/'/'/g;
1757 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1758 # utf8::decode( @$values[$i] );
1760 if ( ( @$tags[$i] ne $prevtag ) ) {
1761 $j++ unless ( @$tags[$i] eq "" );
1762 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
1763 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
1764 my $ind1 = _default_ind_to_space($indicator1);
1766 if ( @$indicator[$j] ) {
1767 $ind2 = _default_ind_to_space($indicator2);
1769 warn "Indicator in @$tags[$i] is empty";
1773 $xml .= "</datafield>\n";
1774 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1775 && ( @$values[$i] ne "" ) ) {
1776 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1777 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1783 if ( @$values[$i] ne "" ) {
1786 if ( @$tags[$i] eq "000" ) {
1787 $xml .= "<leader>@$values[$i]</leader>\n";
1790 # rest of the fixed fields
1791 } elsif ( @$tags[$i] < 10 ) {
1792 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1795 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1796 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1801 } else { # @$tags[$i] eq $prevtag
1802 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
1803 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
1804 my $ind1 = _default_ind_to_space($indicator1);
1806 if ( @$indicator[$j] ) {
1807 $ind2 = _default_ind_to_space($indicator2);
1809 warn "Indicator in @$tags[$i] is empty";
1812 if ( @$values[$i] eq "" ) {
1815 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1818 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1821 $prevtag = @$tags[$i];
1823 $xml .= "</datafield>\n" if @$tags > 0;
1824 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist ) {
1826 # warn "SETTING 100 for $auth_type";
1827 my $string = strftime( "%Y%m%d", localtime(time) );
1829 # set 50 to position 26 is biblios, 13 if authorities
1831 $pos = 13 if $auth_type eq 'UNIMARCAUTH';
1832 $string = sprintf( "%-*s", 35, $string );
1833 substr( $string, $pos, 6, "50" );
1834 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1835 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1836 $xml .= "</datafield>\n";
1838 $xml .= "</record>\n";
1839 $xml .= MARC::File::XML::footer();
1843 =head2 _default_ind_to_space
1845 Passed what should be an indicator returns a space
1846 if its undefined or zero length
1850 sub _default_ind_to_space {
1852 if ( !defined $s || $s eq q{} ) {
1858 =head2 TransformHtmlToMarc
1860 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1861 L<$params> is a ref to an array as below:
1863 'tag_010_indicator1_531951' ,
1864 'tag_010_indicator2_531951' ,
1865 'tag_010_code_a_531951_145735' ,
1866 'tag_010_subfield_a_531951_145735' ,
1867 'tag_200_indicator1_873510' ,
1868 'tag_200_indicator2_873510' ,
1869 'tag_200_code_a_873510_673465' ,
1870 'tag_200_subfield_a_873510_673465' ,
1871 'tag_200_code_b_873510_704318' ,
1872 'tag_200_subfield_b_873510_704318' ,
1873 'tag_200_code_e_873510_280822' ,
1874 'tag_200_subfield_e_873510_280822' ,
1875 'tag_200_code_f_873510_110730' ,
1876 'tag_200_subfield_f_873510_110730' ,
1878 L<$cgi> is the CGI object which containts the value.
1879 L<$record> is the MARC::Record object.
1883 sub TransformHtmlToMarc {
1887 # explicitly turn on the UTF-8 flag for all
1888 # 'tag_' parameters to avoid incorrect character
1889 # conversion later on
1890 my $cgi_params = $cgi->Vars;
1891 foreach my $param_name ( keys %$cgi_params ) {
1892 if ( $param_name =~ /^tag_/ ) {
1893 my $param_value = $cgi_params->{$param_name};
1894 if ( utf8::decode($param_value) ) {
1895 $cgi_params->{$param_name} = $param_value;
1898 # FIXME - need to do something if string is not valid UTF-8
1902 # creating a new record
1903 my $record = MARC::Record->new();
1906 while ( $params->[$i] ) { # browse all CGI params
1907 my $param = $params->[$i];
1910 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1911 if ( $param eq 'biblionumber' ) {
1912 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1913 if ( $biblionumbertagfield < 10 ) {
1914 $newfield = MARC::Field->new( $biblionumbertagfield, $cgi->param($param), );
1916 $newfield = MARC::Field->new( $biblionumbertagfield, '', '', "$biblionumbertagsubfield" => $cgi->param($param), );
1918 push @fields, $newfield if ($newfield);
1919 } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..."
1922 my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) );
1923 my $ind2 = _default_ind_to_space( substr( $cgi->param( $params->[ $i + 1 ] ), 0, 1 ) );
1927 if ( $tag < 10 ) { # no code for theses fields
1928 # in MARC editor, 000 contains the leader.
1929 if ( $tag eq '000' ) {
1930 # Force a fake leader even if not provided to avoid crashing
1931 # during decoding MARC record containing UTF-8 characters
1933 length( $cgi->param($params->[$j+1]) ) == 24
1934 ? $cgi->param( $params->[ $j + 1 ] )
1938 # between 001 and 009 (included)
1939 } elsif ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) {
1940 $newfield = MARC::Field->new( $tag, $cgi->param( $params->[ $j + 1 ] ), );
1943 # > 009, deal with subfields
1945 while ( defined $params->[$j] && $params->[$j] =~ /_code_/ ) { # browse all it's subfield
1946 my $inner_param = $params->[$j];
1948 if ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) { # only if there is a value (code => value)
1949 $newfield->add_subfields( $cgi->param($inner_param) => $cgi->param( $params->[ $j + 1 ] ) );
1952 if ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) { # creating only if there is a value (code => value)
1953 $newfield = MARC::Field->new( $tag, $ind1, $ind2, $cgi->param($inner_param) => $cgi->param( $params->[ $j + 1 ] ), );
1959 push @fields, $newfield if ($newfield);
1964 $record->append_fields(@fields);
1968 # cache inverted MARC field map
1969 our $inverted_field_map;
1971 =head2 TransformMarcToKoha
1973 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1975 Extract data from a MARC bib record into a hashref representing
1976 Koha biblio, biblioitems, and items fields.
1980 sub TransformMarcToKoha {
1981 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1984 $limit_table = $limit_table || 0;
1985 $frameworkcode = '' unless defined $frameworkcode;
1987 unless ( defined $inverted_field_map ) {
1988 $inverted_field_map = _get_inverted_marc_field_map();
1992 if ( defined $limit_table && $limit_table eq 'items' ) {
1993 $tables{'items'} = 1;
1995 $tables{'items'} = 1;
1996 $tables{'biblio'} = 1;
1997 $tables{'biblioitems'} = 1;
2000 # traverse through record
2001 MARCFIELD: foreach my $field ( $record->fields() ) {
2002 my $tag = $field->tag();
2003 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2004 if ( $field->is_control_field() ) {
2005 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2006 ENTRY: foreach my $entry ( @{$kohafields} ) {
2007 my ( $subfield, $table, $column ) = @{$entry};
2008 next ENTRY unless exists $tables{$table};
2009 my $key = _disambiguate( $table, $column );
2010 if ( $result->{$key} ) {
2011 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $field->data() eq "" ) ) {
2012 $result->{$key} .= " | " . $field->data();
2015 $result->{$key} = $field->data();
2020 # deal with subfields
2021 MARCSUBFIELD: foreach my $sf ( $field->subfields() ) {
2022 my $code = $sf->[0];
2023 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2024 my $value = $sf->[1];
2025 SFENTRY: foreach my $entry ( @{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} } ) {
2026 my ( $table, $column ) = @{$entry};
2027 next SFENTRY unless exists $tables{$table};
2028 my $key = _disambiguate( $table, $column );
2029 if ( $result->{$key} ) {
2030 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $value eq "" ) ) {
2031 $result->{$key} .= " | " . $value;
2034 $result->{$key} = $value;
2041 # modify copyrightdate to keep only the 1st year found
2042 if ( exists $result->{'copyrightdate'} ) {
2043 my $temp = $result->{'copyrightdate'};
2044 $temp =~ m/c(\d\d\d\d)/;
2045 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2046 $result->{'copyrightdate'} = $1;
2047 } else { # if no cYYYY, get the 1st date.
2048 $temp =~ m/(\d\d\d\d)/;
2049 $result->{'copyrightdate'} = $1;
2053 # modify publicationyear to keep only the 1st year found
2054 if ( exists $result->{'publicationyear'} ) {
2055 my $temp = $result->{'publicationyear'};
2056 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2057 $result->{'publicationyear'} = $1;
2058 } else { # if no cYYYY, get the 1st date.
2059 $temp =~ m/(\d\d\d\d)/;
2060 $result->{'publicationyear'} = $1;
2067 sub _get_inverted_marc_field_map {
2069 my $relations = C4::Context->marcfromkohafield;
2071 foreach my $frameworkcode ( keys %{$relations} ) {
2072 foreach my $kohafield ( keys %{ $relations->{$frameworkcode} } ) {
2073 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2074 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2075 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2076 my ( $table, $column ) = split /[.]/, $kohafield, 2;
2077 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2078 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2084 =head2 _disambiguate
2086 $newkey = _disambiguate($table, $field);
2088 This is a temporary hack to distinguish between the
2089 following sets of columns when using TransformMarcToKoha.
2091 items.cn_source & biblioitems.cn_source
2092 items.cn_sort & biblioitems.cn_sort
2094 Columns that are currently NOT distinguished (FIXME
2095 due to lack of time to fully test) are:
2097 biblio.notes and biblioitems.notes
2102 FIXME - this is necessary because prefixing each column
2103 name with the table name would require changing lots
2104 of code and templates, and exposing more of the DB
2105 structure than is good to the UI templates, particularly
2106 since biblio and bibloitems may well merge in a future
2107 version. In the future, it would also be good to
2108 separate DB access and UI presentation field names
2113 sub CountItemsIssued {
2114 my ($biblionumber) = @_;
2115 my $dbh = C4::Context->dbh;
2116 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2117 $sth->execute($biblionumber);
2118 my $row = $sth->fetchrow_hashref();
2119 return $row->{'issuedCount'};
2123 my ( $table, $column ) = @_;
2124 if ( $column eq "cn_sort" or $column eq "cn_source" ) {
2125 return $table . '.' . $column;
2132 =head2 get_koha_field_from_marc
2134 $result->{_disambiguate($table, $field)} =
2135 get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2137 Internal function to map data from the MARC record to a specific non-MARC field.
2138 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2142 sub get_koha_field_from_marc {
2143 my ( $koha_table, $koha_column, $record, $frameworkcode ) = @_;
2144 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table . '.' . $koha_column, $frameworkcode );
2146 foreach my $field ( $record->field($tagfield) ) {
2147 if ( $field->tag() < 10 ) {
2149 $kohafield .= " | " . $field->data();
2151 $kohafield = $field->data();
2154 if ( $field->subfields ) {
2155 my @subfields = $field->subfields();
2156 foreach my $subfieldcount ( 0 .. $#subfields ) {
2157 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2159 $kohafield .= " | " . $subfields[$subfieldcount][1];
2161 $kohafield = $subfields[$subfieldcount][1];
2171 =head2 TransformMarcToKohaOneField
2173 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2177 sub TransformMarcToKohaOneField {
2179 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2180 # only the 1st will be retrieved...
2181 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2183 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $kohatable . "." . $kohafield, $frameworkcode );
2184 foreach my $field ( $record->field($tagfield) ) {
2185 if ( $field->tag() < 10 ) {
2186 if ( $result->{$kohafield} ) {
2187 $result->{$kohafield} .= " | " . $field->data();
2189 $result->{$kohafield} = $field->data();
2192 if ( $field->subfields ) {
2193 my @subfields = $field->subfields();
2194 foreach my $subfieldcount ( 0 .. $#subfields ) {
2195 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2196 if ( $result->{$kohafield} ) {
2197 $result->{$kohafield} .= " | " . $subfields[$subfieldcount][1];
2199 $result->{$kohafield} = $subfields[$subfieldcount][1];
2209 =head1 OTHER FUNCTIONS
2212 =head2 PrepareItemrecordDisplay
2214 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2216 Returns a hash with all the fields for Display a given item data in a template
2218 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2222 sub PrepareItemrecordDisplay {
2224 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2226 my $dbh = C4::Context->dbh;
2227 $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2228 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2229 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2231 # return nothing if we don't have found an existing framework.
2232 return "" unless $tagslib;
2233 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum ) if ($itemnum);
2235 my $authorised_values_sth = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib" );
2236 foreach my $tag ( sort keys %{$tagslib} ) {
2237 my $previous_tag = '';
2240 # loop through each subfield
2242 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2243 next if ( subfield_is_koha_internal_p($subfield) );
2244 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2246 $subfield_data{tag} = $tag;
2247 $subfield_data{subfield} = $subfield;
2248 $subfield_data{countsubfield} = $cntsubf++;
2249 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2251 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2252 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2253 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2254 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2255 $subfield_data{hidden} = "display:none"
2256 if $tagslib->{$tag}->{$subfield}->{hidden};
2257 my ( $x, $defaultvalue );
2259 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2261 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2262 if ( !defined $defaultvalue ) {
2263 $defaultvalue = q||;
2265 $defaultvalue =~ s/"/"/g;
2267 # search for itemcallnumber if applicable
2268 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2269 && C4::Context->preference('itemcallnumber') ) {
2270 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2271 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2272 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2274 $defaultvalue = $temp->subfield($CNsubfield);
2277 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2279 && $defaultvalues->{'callnumber'} ) {
2280 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2282 $defaultvalue = $defaultvalues->{'callnumber'} if $defaultvalues;
2285 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2287 && $defaultvalues->{'branchcode'} ) {
2288 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2290 $defaultvalue = $defaultvalues->{branchcode} if $defaultvalues;
2293 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2295 && $defaultvalues->{'location'} ) {
2296 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2298 $defaultvalue = $defaultvalues->{location} if $defaultvalues;
2301 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2302 my @authorised_values;
2305 # builds list, depending on authorised value...
2307 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2308 if ( ( C4::Context->preference("IndependantBranches") )
2309 && ( C4::Context->userenv->{flags} % 2 != 1 ) ) {
2310 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2311 $sth->execute( C4::Context->userenv->{branch} );
2312 push @authorised_values, ""
2313 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2314 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2315 push @authorised_values, $branchcode;
2316 $authorised_lib{$branchcode} = $branchname;
2319 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2321 push @authorised_values, ""
2322 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2323 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2324 push @authorised_values, $branchcode;
2325 $authorised_lib{$branchcode} = $branchname;
2330 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2331 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2333 push @authorised_values, ""
2334 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2335 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2336 push @authorised_values, $itemtype;
2337 $authorised_lib{$itemtype} = $description;
2340 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2341 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2343 my $class_sources = GetClassSources();
2344 my $default_source = C4::Context->preference("DefaultClassificationSource");
2346 foreach my $class_source (sort keys %$class_sources) {
2347 next unless $class_sources->{$class_source}->{'used'} or
2348 ($class_source eq $default_source);
2349 push @authorised_values, $class_source;
2350 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2353 #---- "true" authorised value
2355 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
2356 push @authorised_values, ""
2357 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2358 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2359 push @authorised_values, $value;
2360 $authorised_lib{$value} = $lib;
2363 $subfield_data{marc_value} = CGI::scrolling_list(
2364 -name => 'field_value',
2365 -values => \@authorised_values,
2366 -default => "$defaultvalue",
2367 -labels => \%authorised_lib,
2373 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2375 push( @loop_data, \%subfield_data );
2379 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2380 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2382 'itemtagfield' => $itemtagfield,
2383 'itemtagsubfield' => $itemtagsubfield,
2384 'itemnumber' => $itemnumber,
2385 'iteminformation' => \@loop_data
2392 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2394 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2395 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2396 # =head2 ModZebrafiles
2398 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2402 # sub ModZebrafiles {
2404 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2408 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2409 # unless ( opendir( DIR, "$zebradir" ) ) {
2410 # warn "$zebradir not found";
2414 # my $filename = $zebradir . $biblionumber;
2417 # open( OUTPUT, ">", $filename . ".xml" );
2418 # print OUTPUT $record;
2425 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2427 $biblionumber is the biblionumber we want to index
2429 $op is specialUpdate or delete, and is used to know what we want to do
2431 $server is the server that we want to update
2433 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2434 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2437 $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.
2442 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2443 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2444 my $dbh = C4::Context->dbh;
2446 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2448 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2449 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2451 if ( C4::Context->preference("NoZebra") ) {
2453 # lock the nozebra table : we will read index lines, update them in Perl process
2454 # and write everything in 1 transaction.
2455 # lock the table to avoid someone else overwriting what we are doing
2456 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2457 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2458 if ( $op eq 'specialUpdate' ) {
2460 # OK, we have to add or update the record
2461 # 1st delete (virtually, in indexes), if record actually exists
2463 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2466 # ... add the record
2467 %result = _AddBiblioNoZebra( $biblionumber, $newRecord, $server, %result );
2470 # it's a deletion, delete the record...
2471 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2472 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2475 # ok, now update the database...
2476 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2477 foreach my $key ( keys %result ) {
2478 foreach my $index ( keys %{ $result{$key} } ) {
2479 $sth->execute( $result{$key}->{$index}, $server, $key, $index );
2482 $dbh->do('UNLOCK TABLES');
2486 # we use zebra, just fill zebraqueue table
2488 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2490 AND biblio_auth_number = ?
2493 my $check_sth = $dbh->prepare_cached($check_sql);
2494 $check_sth->execute( $server, $biblionumber, $op );
2495 my ($count) = $check_sth->fetchrow_array;
2496 $check_sth->finish();
2497 if ( $count == 0 ) {
2498 my $sth = $dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2499 $sth->execute( $biblionumber, $server, $op );
2505 =head2 GetNoZebraIndexes
2507 %indexes = GetNoZebraIndexes;
2509 return the data from NoZebraIndexes syspref.
2513 sub GetNoZebraIndexes {
2514 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2516 INDEX: foreach my $line ( split /['"],[\n\r]*/, $no_zebra_indexes ) {
2517 $line =~ /(.*)=>(.*)/;
2518 my $index = $1; # initial ' or " is removed afterwards
2520 $index =~ s/'|"|\s//g;
2521 $fields =~ s/'|"|\s//g;
2522 $indexes{$index} = $fields;
2527 =head1 INTERNAL FUNCTIONS
2529 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2531 function to delete a biblio in NoZebra indexes
2532 This function does NOT delete anything in database : it reads all the indexes entries
2533 that have to be deleted & delete them in the hash
2535 The SQL part is done either :
2536 - after the Add if we are modifying a biblio (delete + add again)
2537 - immediatly after this sub if we are doing a true deletion.
2539 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2543 sub _DelBiblioNoZebra {
2544 my ( $biblionumber, $record, $server ) = @_;
2547 my $dbh = C4::Context->dbh;
2552 if ( $server eq 'biblioserver' ) {
2553 %index = GetNoZebraIndexes;
2555 # get title of the record (to store the 10 first letters with the index)
2556 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2557 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2560 # for authorities, the "title" is the $a mainentry
2561 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2562 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2563 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2564 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2565 $index{'mainmainentry'} = $authref->{'auth_tag_to_report'} . 'a';
2566 $index{'mainentry'} = $authref->{'auth_tag_to_report'} . '*';
2567 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2572 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2573 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2575 # limit to 10 char, should be enough, and limit the DB size
2576 $title = substr( $title, 0, 10 );
2579 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2580 foreach my $field ( $record->fields() ) {
2582 #parse each subfield
2583 next if $field->tag < 10;
2584 foreach my $subfield ( $field->subfields() ) {
2585 my $tag = $field->tag();
2586 my $subfieldcode = $subfield->[0];
2589 # check each index to see if the subfield is stored somewhere
2590 # otherwise, store it in __RAW__ index
2591 foreach my $key ( keys %index ) {
2593 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2594 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2596 my $line = lc $subfield->[1];
2598 # remove meaningless value in the field...
2599 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2601 # ... and split in words
2602 foreach ( split / /, $line ) {
2603 next unless $_; # skip empty values (multiple spaces)
2604 # if the entry is already here, do nothing, the biblionumber has already be removed
2605 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/ ) ) {
2607 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2608 $sth2->execute( $server, $key, $_ );
2609 my $existing_biblionumbers = $sth2->fetchrow;
2612 if ($existing_biblionumbers) {
2614 # warn " existing for $key $_: $existing_biblionumbers";
2615 $result{$key}->{$_} = $existing_biblionumbers;
2616 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2623 # the subfield is not indexed, store it in __RAW__ index anyway
2625 my $line = lc $subfield->[1];
2626 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2628 # ... and split in words
2629 foreach ( split / /, $line ) {
2630 next unless $_; # skip empty values (multiple spaces)
2631 # if the entry is already here, do nothing, the biblionumber has already be removed
2632 unless ( $result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/ ) {
2634 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2635 $sth2->execute( $server, '__RAW__', $_ );
2636 my $existing_biblionumbers = $sth2->fetchrow;
2639 if ($existing_biblionumbers) {
2640 $result{'__RAW__'}->{$_} = $existing_biblionumbers;
2641 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2651 =head2 _AddBiblioNoZebra
2653 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2655 function to add a biblio in NoZebra indexes
2659 sub _AddBiblioNoZebra {
2660 my ( $biblionumber, $record, $server, %result ) = @_;
2661 my $dbh = C4::Context->dbh;
2666 if ( $server eq 'biblioserver' ) {
2667 %index = GetNoZebraIndexes;
2669 # get title of the record (to store the 10 first letters with the index)
2670 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2671 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2674 # warn "server : $server";
2675 # for authorities, the "title" is the $a mainentry
2676 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2677 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2678 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2679 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2680 $index{'mainmainentry'} = $authref->{auth_tag_to_report} . 'a';
2681 $index{'mainentry'} = $authref->{auth_tag_to_report} . '*';
2682 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2685 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2686 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2688 # limit to 10 char, should be enough, and limit the DB size
2689 $title = substr( $title, 0, 10 );
2692 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2693 foreach my $field ( $record->fields() ) {
2695 #parse each subfield
2696 ###FIXME: impossible to index a 001-009 value with NoZebra
2697 next if $field->tag < 10;
2698 foreach my $subfield ( $field->subfields() ) {
2699 my $tag = $field->tag();
2700 my $subfieldcode = $subfield->[0];
2703 # warn "INDEXING :".$subfield->[1];
2704 # check each index to see if the subfield is stored somewhere
2705 # otherwise, store it in __RAW__ index
2706 foreach my $key ( keys %index ) {
2708 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2709 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2711 my $line = lc $subfield->[1];
2713 # remove meaningless value in the field...
2714 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /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, improve weight
2721 # warn "managing $_";
2722 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
2723 my $weight = $1 + 1;
2724 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2725 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2728 # get the value if it exist in the nozebra table, otherwise, create it
2729 $sth2->execute( $server, $key, $_ );
2730 my $existing_biblionumbers = $sth2->fetchrow;
2733 if ($existing_biblionumbers) {
2734 $result{$key}->{"$_"} = $existing_biblionumbers;
2735 my $weight = defined $1 ? $1 + 1 : 1;
2736 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2737 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2739 # create a new ligne for this entry
2742 # warn "INSERT : $server / $key / $_";
2743 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname=' . $dbh->quote($key) . ',value=' . $dbh->quote($_) );
2744 $result{$key}->{"$_"} .= "$biblionumber,$title-1;";
2751 # the subfield is not indexed, store it in __RAW__ index anyway
2753 my $line = lc $subfield->[1];
2754 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2756 # ... and split in words
2757 foreach ( split / /, $line ) {
2758 next unless $_; # skip empty values (multiple spaces)
2759 # if the entry is already here, improve weight
2760 my $tmpstr = $result{'__RAW__'}->{"$_"} || "";
2761 if ( $tmpstr =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
2762 my $weight = $1 + 1;
2763 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2764 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2767 # get the value if it exist in the nozebra table, otherwise, create it
2768 $sth2->execute( $server, '__RAW__', $_ );
2769 my $existing_biblionumbers = $sth2->fetchrow;
2772 if ($existing_biblionumbers) {
2773 $result{'__RAW__'}->{"$_"} = $existing_biblionumbers;
2774 my $weight = ( $1 ? $1 : 0 ) + 1;
2775 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2776 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2778 # create a new ligne for this entry
2780 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname="__RAW__",value=' . $dbh->quote($_) );
2781 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-1;";
2793 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2795 Find the given $subfield in the given $tag in the given
2796 MARC::Record $record. If the subfield is found, returns
2797 the (indicators, value) pair; otherwise, (undef, undef) is
2801 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2802 I suggest we export it from this module.
2807 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2810 if ( $tagfield < 10 ) {
2811 if ( $record->field($tagfield) ) {
2812 push @result, $record->field($tagfield)->data();
2817 foreach my $field ( $record->field($tagfield) ) {
2818 my @subfields = $field->subfields();
2819 foreach my $subfield (@subfields) {
2820 if ( @$subfield[0] eq $insubfield ) {
2821 push @result, @$subfield[1];
2822 $indicator = $field->indicator(1) . $field->indicator(2);
2827 return ( $indicator, @result );
2830 =head2 _koha_marc_update_bib_ids
2833 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2835 Internal function to add or update biblionumber and biblioitemnumber to
2840 sub _koha_marc_update_bib_ids {
2841 my ( $record, $frameworkcode, $biblionumber, $biblioitemnumber ) = @_;
2843 # we must add bibnum and bibitemnum in MARC::Record...
2844 # we build the new field with biblionumber and biblioitemnumber
2845 # we drop the original field
2846 # we add the new builded field.
2847 my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
2848 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
2850 if ( $biblio_tag != $biblioitem_tag ) {
2852 # biblionumber & biblioitemnumber are in different fields
2854 # deal with biblionumber
2855 my ( $new_field, $old_field );
2856 if ( $biblio_tag < 10 ) {
2857 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2859 $new_field = MARC::Field->new( $biblio_tag, '', '', "$biblio_subfield" => $biblionumber );
2862 # drop old field and create new one...
2863 $old_field = $record->field($biblio_tag);
2864 $record->delete_field($old_field) if $old_field;
2865 $record->append_fields($new_field);
2867 # deal with biblioitemnumber
2868 if ( $biblioitem_tag < 10 ) {
2869 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2871 $new_field = MARC::Field->new( $biblioitem_tag, '', '', "$biblioitem_subfield" => $biblioitemnumber, );
2874 # drop old field and create new one...
2875 $old_field = $record->field($biblioitem_tag);
2876 $record->delete_field($old_field) if $old_field;
2877 $record->insert_fields_ordered($new_field);
2881 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2882 my $new_field = MARC::Field->new(
2883 $biblio_tag, '', '',
2884 "$biblio_subfield" => $biblionumber,
2885 "$biblioitem_subfield" => $biblioitemnumber
2888 # drop old field and create new one...
2889 my $old_field = $record->field($biblio_tag);
2890 $record->delete_field($old_field) if $old_field;
2891 $record->insert_fields_ordered($new_field);
2895 =head2 _koha_marc_update_biblioitem_cn_sort
2897 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2899 Given a MARC bib record and the biblioitem hash, update the
2900 subfield that contains a copy of the value of biblioitems.cn_sort.
2904 sub _koha_marc_update_biblioitem_cn_sort {
2906 my $biblioitem = shift;
2907 my $frameworkcode = shift;
2909 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.cn_sort", $frameworkcode );
2910 return unless $biblioitem_tag;
2912 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2914 if ( my $field = $marc->field($biblioitem_tag) ) {
2915 $field->delete_subfield( code => $biblioitem_subfield );
2916 if ( $cn_sort ne '' ) {
2917 $field->add_subfields( $biblioitem_subfield => $cn_sort );
2921 # if we get here, no biblioitem tag is present in the MARC record, so
2922 # we'll create it if $cn_sort is not empty -- this would be
2923 # an odd combination of events, however
2925 $marc->insert_grouped_field( MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) );
2930 =head2 _koha_add_biblio
2932 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2934 Internal function to add a biblio ($biblio is a hash with the values)
2938 sub _koha_add_biblio {
2939 my ( $dbh, $biblio, $frameworkcode ) = @_;
2943 # set the series flag
2944 unless (defined $biblio->{'serial'}){
2945 $biblio->{'serial'} = 0;
2946 if ( $biblio->{'seriestitle'} ) { $biblio->{'serial'} = 1 }
2949 my $query = "INSERT INTO biblio
2950 SET frameworkcode = ?,
2961 my $sth = $dbh->prepare($query);
2963 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
2964 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}
2967 my $biblionumber = $dbh->{'mysql_insertid'};
2968 if ( $dbh->errstr ) {
2969 $error .= "ERROR in _koha_add_biblio $query" . $dbh->errstr;
2975 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2976 return ( $biblionumber, $error );
2979 =head2 _koha_modify_biblio
2981 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2983 Internal function for updating the biblio table
2987 sub _koha_modify_biblio {
2988 my ( $dbh, $biblio, $frameworkcode ) = @_;
2993 SET frameworkcode = ?,
3002 WHERE biblionumber = ?
3005 my $sth = $dbh->prepare($query);
3008 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
3009 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}, $biblio->{'biblionumber'}
3010 ) if $biblio->{'biblionumber'};
3012 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3013 $error .= "ERROR in _koha_modify_biblio $query" . $dbh->errstr;
3016 return ( $biblio->{'biblionumber'}, $error );
3019 =head2 _koha_modify_biblioitem_nonmarc
3021 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3023 Updates biblioitems row except for marc and marcxml, which should be changed
3028 sub _koha_modify_biblioitem_nonmarc {
3029 my ( $dbh, $biblioitem ) = @_;
3032 # re-calculate the cn_sort, it may have changed
3033 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3035 my $query = "UPDATE biblioitems
3036 SET biblionumber = ?,
3042 publicationyear = ?,
3046 collectiontitle = ?,
3048 collectionvolume= ?,
3049 editionstatement= ?,
3050 editionresponsibility = ?,
3064 where biblioitemnumber = ?
3066 my $sth = $dbh->prepare($query);
3068 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3069 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3070 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3071 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3072 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3073 $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'},
3074 $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'},
3075 $biblioitem->{'biblioitemnumber'}
3077 if ( $dbh->errstr ) {
3078 $error .= "ERROR in _koha_modify_biblioitem_nonmarc $query" . $dbh->errstr;
3081 return ( $biblioitem->{'biblioitemnumber'}, $error );
3084 =head2 _koha_add_biblioitem
3086 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3088 Internal function to add a biblioitem
3092 sub _koha_add_biblioitem {
3093 my ( $dbh, $biblioitem ) = @_;
3096 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3097 my $query = "INSERT INTO biblioitems SET
3104 publicationyear = ?,
3108 collectiontitle = ?,
3110 collectionvolume= ?,
3111 editionstatement= ?,
3112 editionresponsibility = ?,
3128 my $sth = $dbh->prepare($query);
3130 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3131 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3132 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3133 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3134 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3135 $biblioitem->{'lccn'}, $biblioitem->{'marc'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'},
3136 $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort,
3137 $biblioitem->{'totalissues'}
3139 my $bibitemnum = $dbh->{'mysql_insertid'};
3141 if ( $dbh->errstr ) {
3142 $error .= "ERROR in _koha_add_biblioitem $query" . $dbh->errstr;
3146 return ( $bibitemnum, $error );
3149 =head2 _koha_delete_biblio
3151 $error = _koha_delete_biblio($dbh,$biblionumber);
3153 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3155 C<$dbh> - the database handle
3157 C<$biblionumber> - the biblionumber of the biblio to be deleted
3161 # FIXME: add error handling
3163 sub _koha_delete_biblio {
3164 my ( $dbh, $biblionumber ) = @_;
3166 # get all the data for this biblio
3167 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3168 $sth->execute($biblionumber);
3170 if ( my $data = $sth->fetchrow_hashref ) {
3172 # save the record in deletedbiblio
3173 # find the fields to save
3174 my $query = "INSERT INTO deletedbiblio SET ";
3176 foreach my $temp ( keys %$data ) {
3177 $query .= "$temp = ?,";
3178 push( @bind, $data->{$temp} );
3181 # replace the last , by ",?)"
3183 my $bkup_sth = $dbh->prepare($query);
3184 $bkup_sth->execute(@bind);
3188 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3189 $del_sth->execute($biblionumber);
3196 =head2 _koha_delete_biblioitems
3198 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3200 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3202 C<$dbh> - the database handle
3203 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3207 # FIXME: add error handling
3209 sub _koha_delete_biblioitems {
3210 my ( $dbh, $biblioitemnumber ) = @_;
3212 # get all the data for this biblioitem
3213 my $sth = $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3214 $sth->execute($biblioitemnumber);
3216 if ( my $data = $sth->fetchrow_hashref ) {
3218 # save the record in deletedbiblioitems
3219 # find the fields to save
3220 my $query = "INSERT INTO deletedbiblioitems SET ";
3222 foreach my $temp ( keys %$data ) {
3223 $query .= "$temp = ?,";
3224 push( @bind, $data->{$temp} );
3227 # replace the last , by ",?)"
3229 my $bkup_sth = $dbh->prepare($query);
3230 $bkup_sth->execute(@bind);
3233 # delete the biblioitem
3234 my $del_sth = $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3235 $del_sth->execute($biblioitemnumber);
3242 =head1 UNEXPORTED FUNCTIONS
3244 =head2 ModBiblioMarc
3246 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3248 Add MARC data for a biblio to koha
3250 Function exported, but should NOT be used, unless you really know what you're doing
3256 # pass the MARC::Record to this function, and it will create the records in the marc field
3257 my ( $record, $biblionumber, $frameworkcode ) = @_;
3258 my $dbh = C4::Context->dbh;
3259 my @fields = $record->fields();
3260 if ( !$frameworkcode ) {
3261 $frameworkcode = "";
3263 my $sth = $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3264 $sth->execute( $frameworkcode, $biblionumber );
3266 my $encoding = C4::Context->preference("marcflavour");
3268 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3269 if ( $encoding eq "UNIMARC" ) {
3270 my $string = $record->subfield( 100, "a" );
3271 if ( ($string) && ( length( $record->subfield( 100, "a" ) ) == 36 ) ) {
3272 my $f100 = $record->field(100);
3273 $record->delete_field($f100);
3275 $string = POSIX::strftime( "%Y%m%d", localtime );
3277 $string = sprintf( "%-*s", 35, $string );
3279 substr( $string, 22, 6, "frey50" );
3280 unless ( $record->subfield( 100, "a" ) ) {
3281 $record->insert_grouped_field( MARC::Field->new( 100, "", "", "a" => $string ) );
3285 #enhancement 5374: update transaction date (005) for marc21/unimarc
3286 if($encoding =~ /MARC21|UNIMARC/) {
3287 my @a= (localtime) [5,4,3,2,1,0]; $a[0]+=1900; $a[1]++;
3288 # YY MM DD HH MM SS (update year and month)
3289 my $f005= $record->field('005');
3290 $f005->update(sprintf("%4d%02d%02d%02d%02d%04.1f",@a)) if $f005;
3294 if ( C4::Context->preference("NoZebra") ) {
3296 # only NoZebra indexing needs to have
3297 # the previous version of the record
3298 $oldRecord = GetMarcBiblio($biblionumber);
3300 $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3301 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding), $biblionumber );
3303 ModZebra( $biblionumber, "specialUpdate", "biblioserver", $oldRecord, $record );
3304 return $biblionumber;
3307 =head2 z3950_extended_services
3309 z3950_extended_services($serviceType,$serviceOptions,$record);
3311 z3950_extended_services is used to handle all interactions with Zebra's extended serices package, which is employed to perform all management of the MARC data stored in Zebra.
3313 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3315 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3317 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3321 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3322 syntax => the record syntax (transfer syntax)
3323 databaseName = Database from connection object
3325 To set serviceOptions, call set_service_options($serviceType)
3327 C<$record> the record, if one is needed for the service type
3329 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3333 sub z3950_extended_services {
3334 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3336 # get our connection object
3337 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3339 # create a new package object
3340 my $Zpackage = $Zconn->package();
3343 $Zpackage->option( action => $action );
3345 if ( $serviceOptions->{'databaseName'} ) {
3346 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3348 if ( $serviceOptions->{'recordIdNumber'} ) {
3349 $Zpackage->option( recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3351 if ( $serviceOptions->{'recordIdOpaque'} ) {
3352 $Zpackage->option( recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3355 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3356 #if ($serviceType eq 'itemorder') {
3357 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3358 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3359 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3360 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3363 if ( $serviceOptions->{record} ) {
3364 $Zpackage->option( record => $serviceOptions->{record} );
3366 # can be xml or marc
3367 if ( $serviceOptions->{'syntax'} ) {
3368 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3372 # send the request, handle any exception encountered
3373 eval { $Zpackage->send($serviceType) };
3374 if ( $@ && $@->isa("ZOOM::Exception") ) {
3375 return "error: " . $@->code() . " " . $@->message() . "\n";
3378 # free up package resources
3379 $Zpackage->destroy();
3382 =head2 set_service_options
3384 my $serviceOptions = set_service_options($serviceType);
3386 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3388 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3392 sub set_service_options {
3393 my ($serviceType) = @_;
3396 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3397 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3399 if ( $serviceType eq 'commit' ) {
3403 if ( $serviceType eq 'create' ) {
3407 if ( $serviceType eq 'drop' ) {
3408 die "ERROR: 'drop' not currently supported (by Zebra)";
3410 return $serviceOptions;
3413 =head2 get_biblio_authorised_values
3415 find the types and values for all authorised values assigned to this biblio.
3419 MARC::Record of the bib
3421 returns: a hashref mapping the authorised value to the value set for this biblionumber
3423 $authorised_values = {
3424 'Scent' => 'flowery',
3425 'Audience' => 'Young Adult',
3426 'itemtypes' => 'SER',
3429 Notes: forlibrarian should probably be passed in, and called something different.
3433 sub get_biblio_authorised_values {
3434 my $biblionumber = shift;
3437 my $forlibrarian = 1; # are we in staff or opac?
3438 my $frameworkcode = GetFrameworkCode($biblionumber);
3440 my $authorised_values;
3442 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3443 or return $authorised_values;
3445 # assume that these entries in the authorised_value table are bibliolevel.
3446 # ones that start with 'item%' are item level.
3447 my $query = q(SELECT distinct authorised_value, kohafield
3448 FROM marc_subfield_structure
3449 WHERE authorised_value !=''
3450 AND (kohafield like 'biblio%'
3451 OR kohafield like '') );
3452 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3454 foreach my $tag ( keys(%$tagslib) ) {
3455 foreach my $subfield ( keys( %{ $tagslib->{$tag} } ) ) {
3457 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3458 if ( 'HASH' eq ref $tagslib->{$tag}{$subfield} ) {
3459 if ( defined $tagslib->{$tag}{$subfield}{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } ) {
3460 if ( defined $record->field($tag) ) {
3461 my $this_subfield_value = $record->field($tag)->subfield($subfield);
3462 if ( defined $this_subfield_value ) {
3463 $authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } = $this_subfield_value;
3471 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3472 return $authorised_values;
3481 Koha Development Team <http://koha-community.org/>
3483 Paul POULAIN paul.poulain@free.fr
3485 Joshua Ferraro jmf@liblime.com