3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 use MARC::File::USMARC;
28 use POSIX qw(strftime);
31 use C4::Dates qw/format_date/;
32 use C4::Log; # logaction
38 use vars qw($VERSION @ISA @EXPORT);
44 @ISA = qw( Exporter );
59 &GetBiblioItemByBiblioNumber
60 &GetBiblioFromItemNumber
61 &GetBiblionumberFromItemnumber
82 &GetAuthorisedValueDesc
86 &GetPublisherNameFromIsbn
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 # update biblionumber and biblioitemnumber in MARC
331 # FIXME - this is assuming a 1 to 1 relationship between
332 # biblios and biblioitems
333 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
334 $sth->execute($biblionumber);
335 my ($biblioitemnumber) = $sth->fetchrow;
337 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
339 # load the koha-table data object
340 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
342 # update MARC subfield that stores biblioitems.cn_sort
343 _koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode );
345 # update the MARC record (that now contains biblio and items) with the new record data
346 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
348 # modify the other koha tables
349 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
350 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
354 =head2 ModBiblioframework
356 ModBiblioframework($biblionumber,$frameworkcode);
358 Exported function to modify a biblio framework
362 sub ModBiblioframework {
363 my ( $biblionumber, $frameworkcode ) = @_;
364 my $dbh = C4::Context->dbh;
365 my $sth = $dbh->prepare( "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?" );
366 $sth->execute( $frameworkcode, $biblionumber );
372 my $error = &DelBiblio($dbh,$biblionumber);
374 Exported function (core API) for deleting a biblio in koha.
375 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
376 Also backs it up to deleted* tables
377 Checks to make sure there are not issues on any of the items
379 C<$error> : undef unless an error occurs
384 my ($biblionumber) = @_;
385 my $dbh = C4::Context->dbh;
386 my $error; # for error handling
388 # First make sure this biblio has no items attached
389 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
390 $sth->execute($biblionumber);
391 if ( my $itemnumber = $sth->fetchrow ) {
393 # Fix this to use a status the template can understand
394 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
397 return $error if $error;
399 # We delete attached subscriptions
400 my $subscriptions = &C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
401 foreach my $subscription (@$subscriptions) {
402 &C4::Serials::DelSubscription( $subscription->{subscriptionid} );
405 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
406 # for at least 2 reasons :
407 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
408 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
409 # 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)
411 if ( C4::Context->preference("NoZebra") ) {
413 # only NoZebra indexing needs to have
414 # the previous version of the record
415 $oldRecord = GetMarcBiblio($biblionumber);
417 ModZebra( $biblionumber, "recordDelete", "biblioserver", $oldRecord, undef );
419 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
420 $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
421 $sth->execute($biblionumber);
422 while ( my $biblioitemnumber = $sth->fetchrow ) {
424 # delete this biblioitem
425 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
426 return $error if $error;
429 # delete biblio from Koha tables and save in deletedbiblio
430 # must do this *after* _koha_delete_biblioitems, otherwise
431 # delete cascade will prevent deletedbiblioitems rows
432 # from being generated by _koha_delete_biblioitems
433 $error = _koha_delete_biblio( $dbh, $biblionumber );
435 logaction( "CATALOGUING", "DELETE", $biblionumber, "" ) if C4::Context->preference("CataloguingLog");
440 =head2 LinkBibHeadingsToAuthorities
442 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
444 Links bib headings to authority records by checking
445 each authority-controlled field in the C<MARC::Record>
446 object C<$marc>, looking for a matching authority record,
447 and setting the linking subfield $9 to the ID of that
450 If no matching authority exists, or if multiple
451 authorities match, no $9 will be added, and any
452 existing one inthe field will be deleted.
454 Returns the number of heading links changed in the
459 sub LinkBibHeadingsToAuthorities {
462 my $num_headings_changed = 0;
463 foreach my $field ( $bib->fields() ) {
464 my $heading = C4::Heading->new_from_bib_field($field);
465 next unless defined $heading;
468 my $current_link = $field->subfield('9');
470 # look for matching authorities
471 my $authorities = $heading->authorities();
473 # want only one exact match
474 if ( $#{$authorities} == 0 ) {
475 my $authority = MARC::Record->new_from_usmarc( $authorities->[0] );
476 my $authid = $authority->field('001')->data();
477 next if defined $current_link and $current_link eq $authid;
479 $field->delete_subfield( code => '9' ) if defined $current_link;
480 $field->add_subfields( '9', $authid );
481 $num_headings_changed++;
483 if ( defined $current_link ) {
484 $field->delete_subfield( code => '9' );
485 $num_headings_changed++;
490 return $num_headings_changed;
493 =head2 GetRecordValue
495 my $values = GetRecordValue($field, $record, $frameworkcode);
497 Get MARC fields from a keyword defined in fieldmapping table.
502 my ( $field, $record, $frameworkcode ) = @_;
503 my $dbh = C4::Context->dbh;
505 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
506 $sth->execute( $frameworkcode, $field );
510 while ( my $row = $sth->fetchrow_hashref ) {
511 foreach my $field ( $record->field( $row->{fieldcode} ) ) {
512 if ( ( $row->{subfieldcode} ne "" && $field->subfield( $row->{subfieldcode} ) ) ) {
513 foreach my $subfield ( $field->subfield( $row->{subfieldcode} ) ) {
514 push @result, { 'subfield' => $subfield };
517 } elsif ( $row->{subfieldcode} eq "" ) {
518 push @result, { 'subfield' => $field->as_string() };
526 =head2 SetFieldMapping
528 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
530 Set a Field to MARC mapping value, if it already exists we don't add a new one.
534 sub SetFieldMapping {
535 my ( $framework, $field, $fieldcode, $subfieldcode ) = @_;
536 my $dbh = C4::Context->dbh;
538 my $sth = $dbh->prepare('SELECT * FROM fieldmapping WHERE fieldcode = ? AND subfieldcode = ? AND frameworkcode = ? AND field = ?');
539 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
540 if ( not $sth->fetchrow_hashref ) {
542 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
544 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
548 =head2 DeleteFieldMapping
550 DeleteFieldMapping($id);
552 Delete a field mapping from an $id.
556 sub DeleteFieldMapping {
558 my $dbh = C4::Context->dbh;
560 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
564 =head2 GetFieldMapping
566 GetFieldMapping($frameworkcode);
568 Get all field mappings for a specified frameworkcode
572 sub GetFieldMapping {
573 my ($framework) = @_;
574 my $dbh = C4::Context->dbh;
576 my $sth = $dbh->prepare('SELECT * FROM fieldmapping where frameworkcode = ?');
577 $sth->execute($framework);
580 while ( my $row = $sth->fetchrow_hashref ) {
588 $data = &GetBiblioData($biblionumber);
590 Returns information about the book with the given biblionumber.
591 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
592 the C<biblio> and C<biblioitems> tables in the
595 In addition, C<$data-E<gt>{subject}> is the list of the book's
596 subjects, separated by C<" , "> (space, comma, space).
597 If there are multiple biblioitems with the given biblionumber, only
598 the first one is considered.
604 my $dbh = C4::Context->dbh;
606 # my $query = C4::Context->preference('item-level_itypes') ?
607 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
609 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
610 # WHERE biblio.biblionumber = ?
611 # AND biblioitems.biblionumber = biblio.biblionumber
614 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
616 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
617 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
618 WHERE biblio.biblionumber = ?
619 AND biblioitems.biblionumber = biblio.biblionumber ";
621 my $sth = $dbh->prepare($query);
622 $sth->execute($bibnum);
624 $data = $sth->fetchrow_hashref;
628 } # sub GetBiblioData
630 =head2 &GetBiblioItemData
632 $itemdata = &GetBiblioItemData($biblioitemnumber);
634 Looks up the biblioitem with the given biblioitemnumber. Returns a
635 reference-to-hash. The keys are the fields from the C<biblio>,
636 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
637 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
642 sub GetBiblioItemData {
643 my ($biblioitemnumber) = @_;
644 my $dbh = C4::Context->dbh;
645 my $query = "SELECT *,biblioitems.notes AS bnotes
646 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
647 unless ( C4::Context->preference('item-level_itypes') ) {
648 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
650 $query .= " WHERE biblioitemnumber = ? ";
651 my $sth = $dbh->prepare($query);
653 $sth->execute($biblioitemnumber);
654 $data = $sth->fetchrow_hashref;
657 } # sub &GetBiblioItemData
659 =head2 GetBiblioItemByBiblioNumber
661 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
665 sub GetBiblioItemByBiblioNumber {
666 my ($biblionumber) = @_;
667 my $dbh = C4::Context->dbh;
668 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
672 $sth->execute($biblionumber);
674 while ( my $data = $sth->fetchrow_hashref ) {
675 push @results, $data;
682 =head2 GetBiblionumberFromItemnumber
687 sub GetBiblionumberFromItemnumber {
688 my ($itemnumber) = @_;
689 my $dbh = C4::Context->dbh;
690 my $sth = $dbh->prepare("Select biblionumber FROM items WHERE itemnumber = ?");
692 $sth->execute($itemnumber);
693 my ($result) = $sth->fetchrow;
697 =head2 GetBiblioFromItemNumber
699 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
701 Looks up the item with the given itemnumber. if undef, try the barcode.
703 C<&itemnodata> returns a reference-to-hash whose keys are the fields
704 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
710 sub GetBiblioFromItemNumber {
711 my ( $itemnumber, $barcode ) = @_;
712 my $dbh = C4::Context->dbh;
715 $sth = $dbh->prepare(
717 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
718 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
719 WHERE items.itemnumber = ?"
721 $sth->execute($itemnumber);
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.barcode = ?"
729 $sth->execute($barcode);
731 my $data = $sth->fetchrow_hashref;
738 $isbd = &GetISBDView($biblionumber);
740 Return the ISBD view which can be included in opac and intranet
745 my ( $biblionumber, $template ) = @_;
746 my $record = GetMarcBiblio($biblionumber);
747 my $itemtype = &GetFrameworkCode($biblionumber);
748 my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch", $itemtype );
749 my $tagslib = &GetMarcStructure( 1, $itemtype );
751 my $ISBD = C4::Context->preference('ISBD');
756 foreach my $isbdfield ( split( /#/, $bloc ) ) {
758 # $isbdfield= /(.?.?.?)/;
759 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
760 my $fieldvalue = $1 || 0;
761 my $subfvalue = $2 || "";
763 my $analysestring = $4;
766 # warn "==> $1 / $2 / $3 / $4";
767 # my $fieldvalue=substr($isbdfield,0,3);
768 if ( $fieldvalue > 0 ) {
769 my $hasputtextbefore = 0;
770 my @fieldslist = $record->field($fieldvalue);
771 @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf );
773 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
774 # warn "FV : $fieldvalue";
775 if ( $subfvalue ne "" ) {
776 foreach my $field (@fieldslist) {
777 foreach my $subfield ( $field->subfield($subfvalue) ) {
778 my $calculated = $analysestring;
779 my $tag = $field->tag();
782 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib );
783 my $tagsubf = $tag . $subfvalue;
784 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
785 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
787 # field builded, store the result
788 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
789 $blocres .= $textbefore;
790 $hasputtextbefore = 1;
793 # remove punctuation at start
794 $calculated =~ s/^( |;|:|\.|-)*//g;
795 $blocres .= $calculated;
800 $blocres .= $textafter if $hasputtextbefore;
802 foreach my $field (@fieldslist) {
803 my $calculated = $analysestring;
804 my $tag = $field->tag();
807 my @subf = $field->subfields;
808 for my $i ( 0 .. $#subf ) {
809 my $valuecode = $subf[$i][1];
810 my $subfieldcode = $subf[$i][0];
811 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib );
812 my $tagsubf = $tag . $subfieldcode;
814 $calculated =~ s/ # replace all {{}} codes by the value code.
815 \{\{$tagsubf\}\} # catch the {{actualcode}}
817 $valuecode # replace by the value code
820 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
821 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
824 # field builded, store the result
825 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
826 $blocres .= $textbefore;
827 $hasputtextbefore = 1;
830 # remove punctuation at start
831 $calculated =~ s/^( |;|:|\.|-)*//g;
832 $blocres .= $calculated;
835 $blocres .= $textafter if $hasputtextbefore;
838 $blocres .= $isbdfield;
843 $res =~ s/\{(.*?)\}//g;
845 $res =~ s/\n/<br\/>/g;
855 ( $count, @results ) = &GetBiblio($biblionumber);
860 my ($biblionumber) = @_;
861 my $dbh = C4::Context->dbh;
862 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
865 $sth->execute($biblionumber);
866 while ( my $data = $sth->fetchrow_hashref ) {
867 $results[$count] = $data;
871 return ( $count, @results );
874 =head2 GetBiblioItemInfosOf
876 GetBiblioItemInfosOf(@biblioitemnumbers);
880 sub GetBiblioItemInfosOf {
881 my @biblioitemnumbers = @_;
884 SELECT biblioitemnumber,
888 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
890 return get_infos_of( $query, 'biblioitemnumber' );
893 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
895 =head2 GetMarcStructure
897 $res = GetMarcStructure($forlibrarian,$frameworkcode);
899 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
900 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
901 $frameworkcode : the framework code to read
905 # cache for results of GetMarcStructure -- needed
907 our $marc_structure_cache;
909 sub GetMarcStructure {
910 my ( $forlibrarian, $frameworkcode ) = @_;
911 my $dbh = C4::Context->dbh;
912 $frameworkcode = "" unless $frameworkcode;
914 if ( defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode} ) {
915 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
918 # my $sth = $dbh->prepare(
919 # "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
920 # $sth->execute($frameworkcode);
921 # my ($total) = $sth->fetchrow;
922 # $frameworkcode = "" unless ( $total > 0 );
923 my $sth = $dbh->prepare(
924 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
925 FROM marc_tag_structure
926 WHERE frameworkcode=?
929 $sth->execute($frameworkcode);
930 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
932 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
933 $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
934 $res->{$tag}->{tab} = "";
935 $res->{$tag}->{mandatory} = $mandatory;
936 $res->{$tag}->{repeatable} = $repeatable;
939 $sth = $dbh->prepare(
940 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
941 FROM marc_subfield_structure
942 WHERE frameworkcode=?
943 ORDER BY tagfield,tagsubfield
947 $sth->execute($frameworkcode);
950 my $authorised_value;
961 ( $tag, $subfield, $liblibrarian, $libopac, $tab, $mandatory, $repeatable, $authorised_value,
962 $authtypecode, $value_builder, $kohafield, $seealso, $hidden, $isurl, $link, $defaultvalue
966 $res->{$tag}->{$subfield}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
967 $res->{$tag}->{$subfield}->{tab} = $tab;
968 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
969 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
970 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
971 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
972 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
973 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
974 $res->{$tag}->{$subfield}->{seealso} = $seealso;
975 $res->{$tag}->{$subfield}->{hidden} = $hidden;
976 $res->{$tag}->{$subfield}->{isurl} = $isurl;
977 $res->{$tag}->{$subfield}->{'link'} = $link;
978 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
981 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
986 =head2 GetUsedMarcStructure
988 The same function as GetMarcStructure except it just takes field
989 in tab 0-9. (used field)
991 my $results = GetUsedMarcStructure($frameworkcode);
993 C<$results> is a ref to an array which each case containts a ref
994 to a hash which each keys is the columns from marc_subfield_structure
996 C<$frameworkcode> is the framework code.
1000 sub GetUsedMarcStructure($) {
1001 my $frameworkcode = shift || '';
1004 FROM marc_subfield_structure
1006 AND frameworkcode = ?
1007 ORDER BY tagfield, tagsubfield
1009 my $sth = C4::Context->dbh->prepare($query);
1010 $sth->execute($frameworkcode);
1011 return $sth->fetchall_arrayref( {} );
1014 =head2 GetMarcFromKohaField
1016 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1018 Returns the MARC fields & subfields mapped to the koha field
1019 for the given frameworkcode
1023 sub GetMarcFromKohaField {
1024 my ( $kohafield, $frameworkcode ) = @_;
1025 return 0, 0 unless $kohafield and defined $frameworkcode;
1026 my $relations = C4::Context->marcfromkohafield;
1027 return ( $relations->{$frameworkcode}->{$kohafield}->[0], $relations->{$frameworkcode}->{$kohafield}->[1] );
1030 =head2 GetMarcBiblio
1032 my $record = GetMarcBiblio($biblionumber);
1034 Returns MARC::Record representing bib identified by
1035 C<$biblionumber>. If no bib exists, returns undef.
1036 The MARC record contains both biblio & item data.
1041 my $biblionumber = shift;
1042 my $dbh = C4::Context->dbh;
1043 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1044 $sth->execute($biblionumber);
1045 my $row = $sth->fetchrow_hashref;
1046 my $marcxml = StripNonXmlChars( $row->{'marcxml'} );
1047 MARC::File::XML->default_record_format( C4::Context->preference('marcflavour') );
1048 my $record = MARC::Record->new();
1051 $record = eval { MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour') ) };
1052 if ($@) { warn " problem with :$biblionumber : $@ \n$marcxml"; }
1054 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1063 my $marcxml = GetXmlBiblio($biblionumber);
1065 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1066 The XML contains both biblio & item datas
1071 my ($biblionumber) = @_;
1072 my $dbh = C4::Context->dbh;
1073 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1074 $sth->execute($biblionumber);
1075 my ($marcxml) = $sth->fetchrow;
1079 =head2 GetCOinSBiblio
1081 my $coins = GetCOinSBiblio($biblionumber);
1083 Returns the COinS(a span) which can be included in a biblio record
1087 sub GetCOinSBiblio {
1088 my ($biblionumber) = @_;
1089 my $record = GetMarcBiblio($biblionumber);
1091 # get the coin format
1093 # can't get a valid MARC::Record object, bail out at this point
1094 warn "We called GetMarcBiblio with a biblionumber that doesn't exist biblionumber=$biblionumber";
1097 my $pos7 = substr $record->leader(), 7, 1;
1098 my $pos6 = substr $record->leader(), 6, 1;
1101 my ( $aulast, $aufirst ) = ( '', '' );
1110 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
1115 'b' => 'manuscript',
1117 'd' => 'manuscript',
1121 'i' => 'audioRecording',
1122 'j' => 'audioRecording',
1125 'm' => 'computerProgram',
1130 'a' => 'journalArticle',
1134 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
1136 if ( $genre eq 'book' ) {
1137 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1140 ##### We must transform mtx to a valable mtx and document type ####
1141 if ( $genre eq 'book' ) {
1143 } elsif ( $genre eq 'journal' ) {
1145 } elsif ( $genre eq 'journalArticle' ) {
1152 $genre = ( $mtx eq 'dc' ) ? "&rft.type=$genre" : "&rft.genre=$genre";
1155 $aulast = $record->subfield( '700', 'a' );
1156 $aufirst = $record->subfield( '700', 'b' );
1157 $oauthors = "&rft.au=$aufirst $aulast";
1160 if ( $record->field('200') ) {
1161 for my $au ( $record->field('200')->subfield('g') ) {
1162 $oauthors .= "&rft.au=$au";
1167 ? "&rft.title=" . $record->subfield( '200', 'a' )
1168 : "&rft.title=" . $record->subfield( '200', 'a' ) . "&rft.btitle=" . $record->subfield( '200', 'a' );
1169 $pubyear = $record->subfield( '210', 'd' );
1170 $publisher = $record->subfield( '210', 'c' );
1171 $isbn = $record->subfield( '010', 'a' );
1172 $issn = $record->subfield( '011', 'a' );
1175 # MARC21 need some improve
1178 $genre = "&rft.genre=book";
1181 if ( $record->field('100') ) {
1182 $oauthors .= "&rft.au=" . $record->subfield( '100', 'a' );
1186 if ( $record->field('700') ) {
1187 for my $au ( $record->field('700')->subfield('a') ) {
1188 $oauthors .= "&rft.au=$au";
1191 $title = "&rft.btitle=" . $record->subfield( '245', 'a' );
1192 $subtitle = $record->subfield( '245', 'b' ) || '';
1193 $title .= $subtitle;
1194 $pubyear = $record->subfield( '260', 'c' ) || '';
1195 $publisher = $record->subfield( '260', 'b' ) || '';
1196 $isbn = $record->subfield( '020', 'a' ) || '';
1197 $issn = $record->subfield( '022', 'a' ) || '';
1201 "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";
1202 $coins_value =~ s/(\ |&[^a])/\+/g;
1203 $coins_value =~ s/\"/\"\;/g;
1205 #<!-- 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="
1207 return $coins_value;
1210 =head2 GetAuthorisedValueDesc
1212 my $subfieldvalue =get_authorised_value_desc(
1213 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category, $opac);
1215 Retrieve the complete description for a given authorised value.
1217 Now takes $category and $value pair too.
1219 my $auth_value_desc =GetAuthorisedValueDesc(
1220 '','', 'DVD' ,'','','CCODE');
1222 If the optional $opac parameter is set to a true value, displays OPAC
1223 descriptions rather than normal ones when they exist.
1227 sub GetAuthorisedValueDesc {
1228 my ( $tag, $subfield, $value, $framework, $tagslib, $category, $opac ) = @_;
1229 my $dbh = C4::Context->dbh;
1233 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1236 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1237 return C4::Branch::GetBranchName($value);
1241 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1242 return getitemtypeinfo($value)->{description};
1245 #---- "true" authorized value
1246 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1249 if ( $category ne "" ) {
1250 my $sth = $dbh->prepare( "SELECT lib, lib_opac FROM authorised_values WHERE category = ? AND authorised_value = ?" );
1251 $sth->execute( $category, $value );
1252 my $data = $sth->fetchrow_hashref;
1253 return ( $opac && $data->{'lib_opac'} ) ? $data->{'lib_opac'} : $data->{'lib'};
1255 return $value; # if nothing is found return the original value
1259 =head2 GetMarcControlnumber
1261 $marccontrolnumber = GetMarcControlnumber($record,$marcflavour);
1263 Get the control number / record Identifier from the MARC record and return it.
1267 sub GetMarcControlnumber {
1268 my ( $record, $marcflavour ) = @_;
1269 my $controlnumber = "";
1270 # Control number or Record identifier are the same field in MARC21 and UNIMARC
1271 # Keep $marcflavour for possible later use
1272 if ($marcflavour eq "MARC21" || $marcflavour eq "UNIMARC") {
1273 my $controlnumberField = $record->field('001');
1274 if ($controlnumberField) {
1275 $controlnumber = $controlnumberField->data();
1278 return $controlnumber;
1283 $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
1285 Get all ISBNs from the MARC record and returns them in an array.
1286 ISBNs stored in differents places depending on MARC flavour
1291 my ( $record, $marcflavour ) = @_;
1293 if ( $marcflavour eq "MARC21" ) {
1295 } else { # assume unimarc if not marc21
1302 foreach my $field ( $record->field($scope) ) {
1303 my $value = $field->as_string();
1304 if ( $isbn ne "" ) {
1305 $marcisbn = { marcisbn => $isbn, };
1306 push @marcisbns, $marcisbn;
1309 if ( $isbn ne $value ) {
1310 $isbn = $isbn . " " . $value;
1315 $marcisbn = { marcisbn => $isbn };
1316 push @marcisbns, $marcisbn; #load last tag into array
1323 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1325 Get all notes from the MARC record and returns them in an array.
1326 The note are stored in differents places depending on MARC flavour
1331 my ( $record, $marcflavour ) = @_;
1333 if ( $marcflavour eq "MARC21" ) {
1335 } else { # assume unimarc if not marc21
1342 foreach my $field ( $record->field($scope) ) {
1343 my $value = $field->as_string();
1344 if ( $note ne "" ) {
1345 $marcnote = { marcnote => $note, };
1346 push @marcnotes, $marcnote;
1349 if ( $note ne $value ) {
1350 $note = $note . " " . $value;
1355 $marcnote = { marcnote => $note };
1356 push @marcnotes, $marcnote; #load last tag into array
1359 } # end GetMarcNotes
1361 =head2 GetMarcSubjects
1363 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1365 Get all subjects from the MARC record and returns them in an array.
1366 The subjects are stored in differents places depending on MARC flavour
1370 sub GetMarcSubjects {
1371 my ( $record, $marcflavour ) = @_;
1372 my ( $mintag, $maxtag );
1373 if ( $marcflavour eq "MARC21" ) {
1376 } else { # assume unimarc if not marc21
1386 foreach my $field ( $record->field('6..') ) {
1387 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1389 my @subfields = $field->subfields();
1393 # if there is an authority link, build the link with an= subfield9
1395 for my $subject_subfield (@subfields) {
1397 # don't load unimarc subfields 3,4,5
1398 next if ( ( $marcflavour eq "UNIMARC" ) and ( $subject_subfield->[0] =~ /2|3|4|5/ ) );
1400 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1401 next if ( ( $marcflavour eq "MARC21" ) and ( $subject_subfield->[0] =~ /2/ ) );
1402 my $code = $subject_subfield->[0];
1403 my $value = $subject_subfield->[1];
1404 my $linkvalue = $value;
1405 $linkvalue =~ s/(\(|\))//g;
1406 my $operator = " and " unless $counter == 0;
1409 @link_loop = ( { 'limit' => 'an', link => "$linkvalue" } );
1411 if ( not $found9 ) {
1412 push @link_loop, { 'limit' => 'su', link => $linkvalue, operator => $operator };
1414 my $separator = C4::Context->preference("authoritysep") unless $counter == 0;
1417 my @this_link_loop = @link_loop;
1418 push @subfields_loop, { code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator } unless ( $subject_subfield->[0] eq 9 );
1422 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1425 return \@marcsubjects;
1426 } #end getMARCsubjects
1428 =head2 GetMarcAuthors
1430 authors = GetMarcAuthors($record,$marcflavour);
1432 Get all authors from the MARC record and returns them in an array.
1433 The authors are stored in differents places depending on MARC flavour
1437 sub GetMarcAuthors {
1438 my ( $record, $marcflavour ) = @_;
1439 my ( $mintag, $maxtag );
1441 # tagslib useful for UNIMARC author reponsabilities
1443 &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.
1444 if ( $marcflavour eq "MARC21" ) {
1447 } elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1455 foreach my $field ( $record->fields ) {
1456 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1459 my @subfields = $field->subfields();
1462 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1463 my $subfield9 = $field->subfield('9');
1464 for my $authors_subfield (@subfields) {
1466 # don't load unimarc subfields 3, 5
1467 next if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /3|5/ ) );
1468 my $subfieldcode = $authors_subfield->[0];
1469 my $value = $authors_subfield->[1];
1470 my $linkvalue = $value;
1471 $linkvalue =~ s/(\(|\))//g;
1472 my $operator = " and " unless $count_auth == 0;
1474 # if we have an authority link, use that as the link, otherwise use standard searching
1476 @link_loop = ( { 'limit' => 'an', link => "$subfield9" } );
1479 # reset $linkvalue if UNIMARC author responsibility
1480 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] eq "4" ) ) {
1481 $linkvalue = "(" . GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) . ")";
1483 push @link_loop, { 'limit' => 'au', link => $linkvalue, operator => $operator };
1485 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib )
1486 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /4/ ) );
1487 my @this_link_loop = @link_loop;
1488 my $separator = C4::Context->preference("authoritysep") unless $count_auth == 0;
1489 push @subfields_loop, { code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator } unless ( $authors_subfield->[0] eq '9' );
1492 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1494 return \@marcauthors;
1499 $marcurls = GetMarcUrls($record,$marcflavour);
1501 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1502 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1507 my ( $record, $marcflavour ) = @_;
1510 for my $field ( $record->field('856') ) {
1512 for my $note ( $field->subfield('z') ) {
1513 push @notes, { note => $note };
1515 my @urls = $field->subfield('u');
1516 foreach my $url (@urls) {
1518 if ( $marcflavour eq 'MARC21' ) {
1519 my $s3 = $field->subfield('3');
1520 my $link = $field->subfield('y');
1521 unless ( $url =~ /^\w+:/ ) {
1522 if ( $field->indicator(1) eq '7' ) {
1523 $url = $field->subfield('2') . "://" . $url;
1524 } elsif ( $field->indicator(1) eq '1' ) {
1525 $url = 'ftp://' . $url;
1528 # properly, this should be if ind1=4,
1529 # however we will assume http protocol since we're building a link.
1530 $url = 'http://' . $url;
1534 # TODO handle ind 2 (relationship)
1539 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1540 $marcurl->{'part'} = $s3 if ($link);
1541 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1543 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1544 $marcurl->{'MARCURL'} = $url;
1546 push @marcurls, $marcurl;
1552 =head2 GetMarcSeries
1554 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1556 Get all series from the MARC record and returns them in an array.
1557 The series are stored in differents places depending on MARC flavour
1562 my ( $record, $marcflavour ) = @_;
1563 my ( $mintag, $maxtag );
1564 if ( $marcflavour eq "MARC21" ) {
1567 } else { # assume unimarc if not marc21
1577 foreach my $field ( $record->field('440'), $record->field('490') ) {
1580 #my $value = $field->subfield('a');
1581 #$marcsubjct = {MARCSUBJCT => $value,};
1582 my @subfields = $field->subfields();
1584 #warn "subfields:".join " ", @$subfields;
1587 for my $series_subfield (@subfields) {
1589 undef $volume_number;
1591 # see if this is an instance of a volume
1592 if ( $series_subfield->[0] eq 'v' ) {
1596 my $code = $series_subfield->[0];
1597 my $value = $series_subfield->[1];
1598 my $linkvalue = $value;
1599 $linkvalue =~ s/(\(|\))//g;
1600 my $operator = " and " unless $counter == 0;
1601 push @link_loop, { link => $linkvalue, operator => $operator };
1602 my $separator = C4::Context->preference("authoritysep") unless $counter == 0;
1603 if ($volume_number) {
1604 push @subfields_loop, { volumenum => $value };
1606 push @subfields_loop, { code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number };
1610 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1612 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1613 #push @marcsubjcts, $marcsubjct;
1617 my $marcseriessarray = \@marcseries;
1618 return $marcseriessarray;
1619 } #end getMARCseriess
1621 =head2 GetFrameworkCode
1623 $frameworkcode = GetFrameworkCode( $biblionumber )
1627 sub GetFrameworkCode {
1628 my ($biblionumber) = @_;
1629 my $dbh = C4::Context->dbh;
1630 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1631 $sth->execute($biblionumber);
1632 my ($frameworkcode) = $sth->fetchrow;
1633 return $frameworkcode;
1636 =head2 GetPublisherNameFromIsbn
1638 $name = GetPublishercodeFromIsbn($isbn);
1645 sub GetPublisherNameFromIsbn($) {
1647 $isbn =~ s/[- _]//g;
1649 my @codes = ( split '-', DisplayISBN($isbn) );
1650 my $code = $codes[0] . $codes[1] . $codes[2];
1651 my $dbh = C4::Context->dbh;
1653 SELECT distinct publishercode
1656 AND publishercode IS NOT NULL
1659 my $sth = $dbh->prepare($query);
1660 $sth->execute("$code%");
1661 my $name = $sth->fetchrow;
1662 return $name if length $name;
1666 =head2 TransformKohaToMarc
1668 $record = TransformKohaToMarc( $hash )
1670 This function builds partial MARC::Record from a hash
1671 Hash entries can be from biblio or biblioitems.
1673 This function is called in acquisition module, to create a basic catalogue entry from user entry
1677 sub TransformKohaToMarc {
1679 my $sth = C4::Context->dbh->prepare( "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?" );
1680 my $record = MARC::Record->new();
1681 SetMarcUnicodeFlag( $record, C4::Context->preference("marcflavour") );
1682 foreach ( keys %{$hash} ) {
1683 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1688 =head2 TransformKohaToMarcOneField
1690 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1694 sub TransformKohaToMarcOneField {
1695 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1696 $frameworkcode = '' unless $frameworkcode;
1700 if ( !defined $sth ) {
1701 my $dbh = C4::Context->dbh;
1702 $sth = $dbh->prepare( "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?" );
1704 $sth->execute( $frameworkcode, $kohafieldname );
1705 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1706 my $tag = $record->field($tagfield);
1708 $tag->update( $tagsubfield => $value );
1709 $record->delete_field($tag);
1710 $record->insert_fields_ordered($tag);
1712 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1718 =head2 TransformHtmlToXml
1720 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator,
1721 $ind_tag, $auth_type )
1723 $auth_type contains :
1727 =item - nothing : rebuild a biblio. In UNIMARC the encoding is in 100$a pos 26/27
1729 =item - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1731 =item - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1737 sub TransformHtmlToXml {
1738 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1739 my $xml = MARC::File::XML::header('UTF-8');
1740 $xml .= "<record>\n";
1741 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1742 MARC::File::XML->default_record_format($auth_type);
1744 # in UNIMARC, field 100 contains the encoding
1745 # check that there is one, otherwise the
1746 # MARC::Record->new_from_xml will fail (and Koha will die)
1747 my $unimarc_and_100_exist = 0;
1748 $unimarc_and_100_exist = 1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1753 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1755 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a" ) {
1757 # if we have a 100 field and it's values are not correct, skip them.
1758 # if we don't have any valid 100 field, we will create a default one at the end
1759 my $enc = substr( @$values[$i], 26, 2 );
1760 if ( $enc eq '01' or $enc eq '50' or $enc eq '03' ) {
1761 $unimarc_and_100_exist = 1;
1766 @$values[$i] =~ s/&/&/g;
1767 @$values[$i] =~ s/</</g;
1768 @$values[$i] =~ s/>/>/g;
1769 @$values[$i] =~ s/"/"/g;
1770 @$values[$i] =~ s/'/'/g;
1772 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1773 # utf8::decode( @$values[$i] );
1775 if ( ( @$tags[$i] ne $prevtag ) ) {
1776 $j++ unless ( @$tags[$i] eq "" );
1777 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
1778 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
1779 my $ind1 = _default_ind_to_space($indicator1);
1781 if ( @$indicator[$j] ) {
1782 $ind2 = _default_ind_to_space($indicator2);
1784 warn "Indicator in @$tags[$i] is empty";
1788 $xml .= "</datafield>\n";
1789 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1790 && ( @$values[$i] ne "" ) ) {
1791 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1792 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1798 if ( @$values[$i] ne "" ) {
1801 if ( @$tags[$i] eq "000" ) {
1802 $xml .= "<leader>@$values[$i]</leader>\n";
1805 # rest of the fixed fields
1806 } elsif ( @$tags[$i] < 10 ) {
1807 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1810 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1811 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1816 } else { # @$tags[$i] eq $prevtag
1817 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
1818 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
1819 my $ind1 = _default_ind_to_space($indicator1);
1821 if ( @$indicator[$j] ) {
1822 $ind2 = _default_ind_to_space($indicator2);
1824 warn "Indicator in @$tags[$i] is empty";
1827 if ( @$values[$i] eq "" ) {
1830 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1833 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1836 $prevtag = @$tags[$i];
1838 $xml .= "</datafield>\n" if @$tags > 0;
1839 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist ) {
1841 # warn "SETTING 100 for $auth_type";
1842 my $string = strftime( "%Y%m%d", localtime(time) );
1844 # set 50 to position 26 is biblios, 13 if authorities
1846 $pos = 13 if $auth_type eq 'UNIMARCAUTH';
1847 $string = sprintf( "%-*s", 35, $string );
1848 substr( $string, $pos, 6, "50" );
1849 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1850 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1851 $xml .= "</datafield>\n";
1853 $xml .= "</record>\n";
1854 $xml .= MARC::File::XML::footer();
1858 =head2 _default_ind_to_space
1860 Passed what should be an indicator returns a space
1861 if its undefined or zero length
1865 sub _default_ind_to_space {
1867 if ( !defined $s || $s eq q{} ) {
1873 =head2 TransformHtmlToMarc
1875 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1876 L<$params> is a ref to an array as below:
1878 'tag_010_indicator1_531951' ,
1879 'tag_010_indicator2_531951' ,
1880 'tag_010_code_a_531951_145735' ,
1881 'tag_010_subfield_a_531951_145735' ,
1882 'tag_200_indicator1_873510' ,
1883 'tag_200_indicator2_873510' ,
1884 'tag_200_code_a_873510_673465' ,
1885 'tag_200_subfield_a_873510_673465' ,
1886 'tag_200_code_b_873510_704318' ,
1887 'tag_200_subfield_b_873510_704318' ,
1888 'tag_200_code_e_873510_280822' ,
1889 'tag_200_subfield_e_873510_280822' ,
1890 'tag_200_code_f_873510_110730' ,
1891 'tag_200_subfield_f_873510_110730' ,
1893 L<$cgi> is the CGI object which containts the value.
1894 L<$record> is the MARC::Record object.
1898 sub TransformHtmlToMarc {
1902 # explicitly turn on the UTF-8 flag for all
1903 # 'tag_' parameters to avoid incorrect character
1904 # conversion later on
1905 my $cgi_params = $cgi->Vars;
1906 foreach my $param_name ( keys %$cgi_params ) {
1907 if ( $param_name =~ /^tag_/ ) {
1908 my $param_value = $cgi_params->{$param_name};
1909 if ( utf8::decode($param_value) ) {
1910 $cgi_params->{$param_name} = $param_value;
1913 # FIXME - need to do something if string is not valid UTF-8
1917 # creating a new record
1918 my $record = MARC::Record->new();
1921 while ( $params->[$i] ) { # browse all CGI params
1922 my $param = $params->[$i];
1925 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1926 if ( $param eq 'biblionumber' ) {
1927 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1928 if ( $biblionumbertagfield < 10 ) {
1929 $newfield = MARC::Field->new( $biblionumbertagfield, $cgi->param($param), );
1931 $newfield = MARC::Field->new( $biblionumbertagfield, '', '', "$biblionumbertagsubfield" => $cgi->param($param), );
1933 push @fields, $newfield if ($newfield);
1934 } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..."
1937 my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) );
1938 my $ind2 = _default_ind_to_space( substr( $cgi->param( $params->[ $i + 1 ] ), 0, 1 ) );
1942 if ( $tag < 10 ) { # no code for theses fields
1943 # in MARC editor, 000 contains the leader.
1944 if ( $tag eq '000' ) {
1945 $record->leader( $cgi->param( $params->[ $j + 1 ] ) ) if length( $cgi->param( $params->[ $j + 1 ] ) ) == 24;
1947 # between 001 and 009 (included)
1948 } elsif ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) {
1949 $newfield = MARC::Field->new( $tag, $cgi->param( $params->[ $j + 1 ] ), );
1952 # > 009, deal with subfields
1954 while ( defined $params->[$j] && $params->[$j] =~ /_code_/ ) { # browse all it's subfield
1955 my $inner_param = $params->[$j];
1957 if ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) { # only if there is a value (code => value)
1958 $newfield->add_subfields( $cgi->param($inner_param) => $cgi->param( $params->[ $j + 1 ] ) );
1961 if ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) { # creating only if there is a value (code => value)
1962 $newfield = MARC::Field->new( $tag, $ind1, $ind2, $cgi->param($inner_param) => $cgi->param( $params->[ $j + 1 ] ), );
1968 push @fields, $newfield if ($newfield);
1973 $record->append_fields(@fields);
1977 # cache inverted MARC field map
1978 our $inverted_field_map;
1980 =head2 TransformMarcToKoha
1982 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1984 Extract data from a MARC bib record into a hashref representing
1985 Koha biblio, biblioitems, and items fields.
1989 sub TransformMarcToKoha {
1990 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1993 $limit_table = $limit_table || 0;
1994 $frameworkcode = '' unless defined $frameworkcode;
1996 unless ( defined $inverted_field_map ) {
1997 $inverted_field_map = _get_inverted_marc_field_map();
2001 if ( defined $limit_table && $limit_table eq 'items' ) {
2002 $tables{'items'} = 1;
2004 $tables{'items'} = 1;
2005 $tables{'biblio'} = 1;
2006 $tables{'biblioitems'} = 1;
2009 # traverse through record
2010 MARCFIELD: foreach my $field ( $record->fields() ) {
2011 my $tag = $field->tag();
2012 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2013 if ( $field->is_control_field() ) {
2014 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2015 ENTRY: foreach my $entry ( @{$kohafields} ) {
2016 my ( $subfield, $table, $column ) = @{$entry};
2017 next ENTRY unless exists $tables{$table};
2018 my $key = _disambiguate( $table, $column );
2019 if ( $result->{$key} ) {
2020 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $field->data() eq "" ) ) {
2021 $result->{$key} .= " | " . $field->data();
2024 $result->{$key} = $field->data();
2029 # deal with subfields
2030 MARCSUBFIELD: foreach my $sf ( $field->subfields() ) {
2031 my $code = $sf->[0];
2032 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2033 my $value = $sf->[1];
2034 SFENTRY: foreach my $entry ( @{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} } ) {
2035 my ( $table, $column ) = @{$entry};
2036 next SFENTRY unless exists $tables{$table};
2037 my $key = _disambiguate( $table, $column );
2038 if ( $result->{$key} ) {
2039 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $value eq "" ) ) {
2040 $result->{$key} .= " | " . $value;
2043 $result->{$key} = $value;
2050 # modify copyrightdate to keep only the 1st year found
2051 if ( exists $result->{'copyrightdate'} ) {
2052 my $temp = $result->{'copyrightdate'};
2053 $temp =~ m/c(\d\d\d\d)/;
2054 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2055 $result->{'copyrightdate'} = $1;
2056 } else { # if no cYYYY, get the 1st date.
2057 $temp =~ m/(\d\d\d\d)/;
2058 $result->{'copyrightdate'} = $1;
2062 # modify publicationyear to keep only the 1st year found
2063 if ( exists $result->{'publicationyear'} ) {
2064 my $temp = $result->{'publicationyear'};
2065 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2066 $result->{'publicationyear'} = $1;
2067 } else { # if no cYYYY, get the 1st date.
2068 $temp =~ m/(\d\d\d\d)/;
2069 $result->{'publicationyear'} = $1;
2076 sub _get_inverted_marc_field_map {
2078 my $relations = C4::Context->marcfromkohafield;
2080 foreach my $frameworkcode ( keys %{$relations} ) {
2081 foreach my $kohafield ( keys %{ $relations->{$frameworkcode} } ) {
2082 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2083 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2084 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2085 my ( $table, $column ) = split /[.]/, $kohafield, 2;
2086 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2087 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2093 =head2 _disambiguate
2095 $newkey = _disambiguate($table, $field);
2097 This is a temporary hack to distinguish between the
2098 following sets of columns when using TransformMarcToKoha.
2100 items.cn_source & biblioitems.cn_source
2101 items.cn_sort & biblioitems.cn_sort
2103 Columns that are currently NOT distinguished (FIXME
2104 due to lack of time to fully test) are:
2106 biblio.notes and biblioitems.notes
2111 FIXME - this is necessary because prefixing each column
2112 name with the table name would require changing lots
2113 of code and templates, and exposing more of the DB
2114 structure than is good to the UI templates, particularly
2115 since biblio and bibloitems may well merge in a future
2116 version. In the future, it would also be good to
2117 separate DB access and UI presentation field names
2122 sub CountItemsIssued {
2123 my ($biblionumber) = @_;
2124 my $dbh = C4::Context->dbh;
2125 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2126 $sth->execute($biblionumber);
2127 my $row = $sth->fetchrow_hashref();
2128 return $row->{'issuedCount'};
2132 my ( $table, $column ) = @_;
2133 if ( $column eq "cn_sort" or $column eq "cn_source" ) {
2134 return $table . '.' . $column;
2141 =head2 get_koha_field_from_marc
2143 $result->{_disambiguate($table, $field)} =
2144 get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2146 Internal function to map data from the MARC record to a specific non-MARC field.
2147 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2151 sub get_koha_field_from_marc {
2152 my ( $koha_table, $koha_column, $record, $frameworkcode ) = @_;
2153 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table . '.' . $koha_column, $frameworkcode );
2155 foreach my $field ( $record->field($tagfield) ) {
2156 if ( $field->tag() < 10 ) {
2158 $kohafield .= " | " . $field->data();
2160 $kohafield = $field->data();
2163 if ( $field->subfields ) {
2164 my @subfields = $field->subfields();
2165 foreach my $subfieldcount ( 0 .. $#subfields ) {
2166 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2168 $kohafield .= " | " . $subfields[$subfieldcount][1];
2170 $kohafield = $subfields[$subfieldcount][1];
2180 =head2 TransformMarcToKohaOneField
2182 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2186 sub TransformMarcToKohaOneField {
2188 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2189 # only the 1st will be retrieved...
2190 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2192 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $kohatable . "." . $kohafield, $frameworkcode );
2193 foreach my $field ( $record->field($tagfield) ) {
2194 if ( $field->tag() < 10 ) {
2195 if ( $result->{$kohafield} ) {
2196 $result->{$kohafield} .= " | " . $field->data();
2198 $result->{$kohafield} = $field->data();
2201 if ( $field->subfields ) {
2202 my @subfields = $field->subfields();
2203 foreach my $subfieldcount ( 0 .. $#subfields ) {
2204 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2205 if ( $result->{$kohafield} ) {
2206 $result->{$kohafield} .= " | " . $subfields[$subfieldcount][1];
2208 $result->{$kohafield} = $subfields[$subfieldcount][1];
2218 =head1 OTHER FUNCTIONS
2221 =head2 PrepareItemrecordDisplay
2223 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2225 Returns a hash with all the fields for Display a given item data in a template
2227 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2231 sub PrepareItemrecordDisplay {
2233 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2235 my $dbh = C4::Context->dbh;
2236 $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2237 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2238 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2240 # return nothing if we don't have found an existing framework.
2241 return "" unless $tagslib;
2242 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum ) if ($itemnum);
2244 my $authorised_values_sth = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib" );
2245 foreach my $tag ( sort keys %{$tagslib} ) {
2246 my $previous_tag = '';
2249 # loop through each subfield
2251 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2252 next if ( subfield_is_koha_internal_p($subfield) );
2253 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2255 $subfield_data{tag} = $tag;
2256 $subfield_data{subfield} = $subfield;
2257 $subfield_data{countsubfield} = $cntsubf++;
2258 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2260 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2261 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2262 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2263 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2264 $subfield_data{hidden} = "display:none"
2265 if $tagslib->{$tag}->{$subfield}->{hidden};
2266 my ( $x, $defaultvalue );
2268 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2270 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2271 if ( !defined $defaultvalue ) {
2272 $defaultvalue = q||;
2274 $defaultvalue =~ s/"/"/g;
2276 # search for itemcallnumber if applicable
2277 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2278 && C4::Context->preference('itemcallnumber') ) {
2279 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2280 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2281 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2283 $defaultvalue = $temp->subfield($CNsubfield);
2286 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2288 && $defaultvalues->{'callnumber'} ) {
2289 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2291 $defaultvalue = $defaultvalues->{'callnumber'} if $defaultvalues;
2294 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2296 && $defaultvalues->{'branchcode'} ) {
2297 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2299 $defaultvalue = $defaultvalues->{branchcode} if $defaultvalues;
2302 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2303 my @authorised_values;
2306 # builds list, depending on authorised value...
2308 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2309 if ( ( C4::Context->preference("IndependantBranches") )
2310 && ( C4::Context->userenv->{flags} % 2 != 1 ) ) {
2311 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2312 $sth->execute( C4::Context->userenv->{branch} );
2313 push @authorised_values, ""
2314 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2315 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2316 push @authorised_values, $branchcode;
2317 $authorised_lib{$branchcode} = $branchname;
2320 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2322 push @authorised_values, ""
2323 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2324 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2325 push @authorised_values, $branchcode;
2326 $authorised_lib{$branchcode} = $branchname;
2331 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2332 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2334 push @authorised_values, ""
2335 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2336 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2337 push @authorised_values, $itemtype;
2338 $authorised_lib{$itemtype} = $description;
2341 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2342 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2344 my $class_sources = GetClassSources();
2345 my $default_source = C4::Context->preference("DefaultClassificationSource");
2347 foreach my $class_source (sort keys %$class_sources) {
2348 next unless $class_sources->{$class_source}->{'used'} or
2349 ($class_source eq $default_source);
2350 push @authorised_values, $class_source;
2351 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2354 #---- "true" authorised value
2356 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
2357 push @authorised_values, ""
2358 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2359 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2360 push @authorised_values, $value;
2361 $authorised_lib{$value} = $lib;
2364 $subfield_data{marc_value} = CGI::scrolling_list(
2365 -name => 'field_value',
2366 -values => \@authorised_values,
2367 -default => "$defaultvalue",
2368 -labels => \%authorised_lib,
2374 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2376 push( @loop_data, \%subfield_data );
2380 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2381 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2383 'itemtagfield' => $itemtagfield,
2384 'itemtagsubfield' => $itemtagsubfield,
2385 'itemnumber' => $itemnumber,
2386 'iteminformation' => \@loop_data
2393 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2395 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2396 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2397 # =head2 ModZebrafiles
2399 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2403 # sub ModZebrafiles {
2405 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2409 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2410 # unless ( opendir( DIR, "$zebradir" ) ) {
2411 # warn "$zebradir not found";
2415 # my $filename = $zebradir . $biblionumber;
2418 # open( OUTPUT, ">", $filename . ".xml" );
2419 # print OUTPUT $record;
2426 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2428 $biblionumber is the biblionumber we want to index
2430 $op is specialUpdate or delete, and is used to know what we want to do
2432 $server is the server that we want to update
2434 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2435 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2438 $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.
2443 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2444 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2445 my $dbh = C4::Context->dbh;
2447 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2449 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2450 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2452 if ( C4::Context->preference("NoZebra") ) {
2454 # lock the nozebra table : we will read index lines, update them in Perl process
2455 # and write everything in 1 transaction.
2456 # lock the table to avoid someone else overwriting what we are doing
2457 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2458 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2459 if ( $op eq 'specialUpdate' ) {
2461 # OK, we have to add or update the record
2462 # 1st delete (virtually, in indexes), if record actually exists
2464 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2467 # ... add the record
2468 %result = _AddBiblioNoZebra( $biblionumber, $newRecord, $server, %result );
2471 # it's a deletion, delete the record...
2472 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2473 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2476 # ok, now update the database...
2477 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2478 foreach my $key ( keys %result ) {
2479 foreach my $index ( keys %{ $result{$key} } ) {
2480 $sth->execute( $result{$key}->{$index}, $server, $key, $index );
2483 $dbh->do('UNLOCK TABLES');
2487 # we use zebra, just fill zebraqueue table
2489 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2491 AND biblio_auth_number = ?
2494 my $check_sth = $dbh->prepare_cached($check_sql);
2495 $check_sth->execute( $server, $biblionumber, $op );
2496 my ($count) = $check_sth->fetchrow_array;
2497 $check_sth->finish();
2498 if ( $count == 0 ) {
2499 my $sth = $dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2500 $sth->execute( $biblionumber, $server, $op );
2506 =head2 GetNoZebraIndexes
2508 %indexes = GetNoZebraIndexes;
2510 return the data from NoZebraIndexes syspref.
2514 sub GetNoZebraIndexes {
2515 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2517 INDEX: foreach my $line ( split /['"],[\n\r]*/, $no_zebra_indexes ) {
2518 $line =~ /(.*)=>(.*)/;
2519 my $index = $1; # initial ' or " is removed afterwards
2521 $index =~ s/'|"|\s//g;
2522 $fields =~ s/'|"|\s//g;
2523 $indexes{$index} = $fields;
2528 =head1 INTERNAL FUNCTIONS
2530 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2532 function to delete a biblio in NoZebra indexes
2533 This function does NOT delete anything in database : it reads all the indexes entries
2534 that have to be deleted & delete them in the hash
2536 The SQL part is done either :
2537 - after the Add if we are modifying a biblio (delete + add again)
2538 - immediatly after this sub if we are doing a true deletion.
2540 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2544 sub _DelBiblioNoZebra {
2545 my ( $biblionumber, $record, $server ) = @_;
2548 my $dbh = C4::Context->dbh;
2553 if ( $server eq 'biblioserver' ) {
2554 %index = GetNoZebraIndexes;
2556 # get title of the record (to store the 10 first letters with the index)
2557 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2558 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2561 # for authorities, the "title" is the $a mainentry
2562 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2563 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2564 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2565 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2566 $index{'mainmainentry'} = $authref->{'auth_tag_to_report'} . 'a';
2567 $index{'mainentry'} = $authref->{'auth_tag_to_report'} . '*';
2568 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2573 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2574 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2576 # limit to 10 char, should be enough, and limit the DB size
2577 $title = substr( $title, 0, 10 );
2580 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2581 foreach my $field ( $record->fields() ) {
2583 #parse each subfield
2584 next if $field->tag < 10;
2585 foreach my $subfield ( $field->subfields() ) {
2586 my $tag = $field->tag();
2587 my $subfieldcode = $subfield->[0];
2590 # check each index to see if the subfield is stored somewhere
2591 # otherwise, store it in __RAW__ index
2592 foreach my $key ( keys %index ) {
2594 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2595 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2597 my $line = lc $subfield->[1];
2599 # remove meaningless value in the field...
2600 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2602 # ... and split in words
2603 foreach ( split / /, $line ) {
2604 next unless $_; # skip empty values (multiple spaces)
2605 # if the entry is already here, do nothing, the biblionumber has already be removed
2606 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/ ) ) {
2608 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2609 $sth2->execute( $server, $key, $_ );
2610 my $existing_biblionumbers = $sth2->fetchrow;
2613 if ($existing_biblionumbers) {
2615 # warn " existing for $key $_: $existing_biblionumbers";
2616 $result{$key}->{$_} = $existing_biblionumbers;
2617 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2624 # the subfield is not indexed, store it in __RAW__ index anyway
2626 my $line = lc $subfield->[1];
2627 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2629 # ... and split in words
2630 foreach ( split / /, $line ) {
2631 next unless $_; # skip empty values (multiple spaces)
2632 # if the entry is already here, do nothing, the biblionumber has already be removed
2633 unless ( $result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/ ) {
2635 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2636 $sth2->execute( $server, '__RAW__', $_ );
2637 my $existing_biblionumbers = $sth2->fetchrow;
2640 if ($existing_biblionumbers) {
2641 $result{'__RAW__'}->{$_} = $existing_biblionumbers;
2642 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2652 =head2 _AddBiblioNoZebra
2654 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2656 function to add a biblio in NoZebra indexes
2660 sub _AddBiblioNoZebra {
2661 my ( $biblionumber, $record, $server, %result ) = @_;
2662 my $dbh = C4::Context->dbh;
2667 if ( $server eq 'biblioserver' ) {
2668 %index = GetNoZebraIndexes;
2670 # get title of the record (to store the 10 first letters with the index)
2671 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2672 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2675 # warn "server : $server";
2676 # for authorities, the "title" is the $a mainentry
2677 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2678 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2679 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2680 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2681 $index{'mainmainentry'} = $authref->{auth_tag_to_report} . 'a';
2682 $index{'mainentry'} = $authref->{auth_tag_to_report} . '*';
2683 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2686 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2687 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2689 # limit to 10 char, should be enough, and limit the DB size
2690 $title = substr( $title, 0, 10 );
2693 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2694 foreach my $field ( $record->fields() ) {
2696 #parse each subfield
2697 ###FIXME: impossible to index a 001-009 value with NoZebra
2698 next if $field->tag < 10;
2699 foreach my $subfield ( $field->subfields() ) {
2700 my $tag = $field->tag();
2701 my $subfieldcode = $subfield->[0];
2704 # warn "INDEXING :".$subfield->[1];
2705 # check each index to see if the subfield is stored somewhere
2706 # otherwise, store it in __RAW__ index
2707 foreach my $key ( keys %index ) {
2709 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2710 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2712 my $line = lc $subfield->[1];
2714 # remove meaningless value in the field...
2715 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2717 # ... and split in words
2718 foreach ( split / /, $line ) {
2719 next unless $_; # skip empty values (multiple spaces)
2720 # if the entry is already here, improve weight
2722 # warn "managing $_";
2723 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
2724 my $weight = $1 + 1;
2725 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2726 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2729 # get the value if it exist in the nozebra table, otherwise, create it
2730 $sth2->execute( $server, $key, $_ );
2731 my $existing_biblionumbers = $sth2->fetchrow;
2734 if ($existing_biblionumbers) {
2735 $result{$key}->{"$_"} = $existing_biblionumbers;
2736 my $weight = defined $1 ? $1 + 1 : 1;
2737 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2738 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2740 # create a new ligne for this entry
2743 # warn "INSERT : $server / $key / $_";
2744 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname=' . $dbh->quote($key) . ',value=' . $dbh->quote($_) );
2745 $result{$key}->{"$_"} .= "$biblionumber,$title-1;";
2752 # the subfield is not indexed, store it in __RAW__ index anyway
2754 my $line = lc $subfield->[1];
2755 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2757 # ... and split in words
2758 foreach ( split / /, $line ) {
2759 next unless $_; # skip empty values (multiple spaces)
2760 # if the entry is already here, improve weight
2761 my $tmpstr = $result{'__RAW__'}->{"$_"} || "";
2762 if ( $tmpstr =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
2763 my $weight = $1 + 1;
2764 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2765 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2768 # get the value if it exist in the nozebra table, otherwise, create it
2769 $sth2->execute( $server, '__RAW__', $_ );
2770 my $existing_biblionumbers = $sth2->fetchrow;
2773 if ($existing_biblionumbers) {
2774 $result{'__RAW__'}->{"$_"} = $existing_biblionumbers;
2775 my $weight = ( $1 ? $1 : 0 ) + 1;
2776 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2777 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2779 # create a new ligne for this entry
2781 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname="__RAW__",value=' . $dbh->quote($_) );
2782 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-1;";
2794 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2796 Find the given $subfield in the given $tag in the given
2797 MARC::Record $record. If the subfield is found, returns
2798 the (indicators, value) pair; otherwise, (undef, undef) is
2802 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2803 I suggest we export it from this module.
2808 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2811 if ( $tagfield < 10 ) {
2812 if ( $record->field($tagfield) ) {
2813 push @result, $record->field($tagfield)->data();
2818 foreach my $field ( $record->field($tagfield) ) {
2819 my @subfields = $field->subfields();
2820 foreach my $subfield (@subfields) {
2821 if ( @$subfield[0] eq $insubfield ) {
2822 push @result, @$subfield[1];
2823 $indicator = $field->indicator(1) . $field->indicator(2);
2828 return ( $indicator, @result );
2831 =head2 _koha_marc_update_bib_ids
2834 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2836 Internal function to add or update biblionumber and biblioitemnumber to
2841 sub _koha_marc_update_bib_ids {
2842 my ( $record, $frameworkcode, $biblionumber, $biblioitemnumber ) = @_;
2844 # we must add bibnum and bibitemnum in MARC::Record...
2845 # we build the new field with biblionumber and biblioitemnumber
2846 # we drop the original field
2847 # we add the new builded field.
2848 my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
2849 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
2851 if ( $biblio_tag != $biblioitem_tag ) {
2853 # biblionumber & biblioitemnumber are in different fields
2855 # deal with biblionumber
2856 my ( $new_field, $old_field );
2857 if ( $biblio_tag < 10 ) {
2858 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2860 $new_field = MARC::Field->new( $biblio_tag, '', '', "$biblio_subfield" => $biblionumber );
2863 # drop old field and create new one...
2864 $old_field = $record->field($biblio_tag);
2865 $record->delete_field($old_field) if $old_field;
2866 $record->append_fields($new_field);
2868 # deal with biblioitemnumber
2869 if ( $biblioitem_tag < 10 ) {
2870 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2872 $new_field = MARC::Field->new( $biblioitem_tag, '', '', "$biblioitem_subfield" => $biblioitemnumber, );
2875 # drop old field and create new one...
2876 $old_field = $record->field($biblioitem_tag);
2877 $record->delete_field($old_field) if $old_field;
2878 $record->insert_fields_ordered($new_field);
2882 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2883 my $new_field = MARC::Field->new(
2884 $biblio_tag, '', '',
2885 "$biblio_subfield" => $biblionumber,
2886 "$biblioitem_subfield" => $biblioitemnumber
2889 # drop old field and create new one...
2890 my $old_field = $record->field($biblio_tag);
2891 $record->delete_field($old_field) if $old_field;
2892 $record->insert_fields_ordered($new_field);
2896 =head2 _koha_marc_update_biblioitem_cn_sort
2898 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2900 Given a MARC bib record and the biblioitem hash, update the
2901 subfield that contains a copy of the value of biblioitems.cn_sort.
2905 sub _koha_marc_update_biblioitem_cn_sort {
2907 my $biblioitem = shift;
2908 my $frameworkcode = shift;
2910 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.cn_sort", $frameworkcode );
2911 return unless $biblioitem_tag;
2913 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2915 if ( my $field = $marc->field($biblioitem_tag) ) {
2916 $field->delete_subfield( code => $biblioitem_subfield );
2917 if ( $cn_sort ne '' ) {
2918 $field->add_subfields( $biblioitem_subfield => $cn_sort );
2922 # if we get here, no biblioitem tag is present in the MARC record, so
2923 # we'll create it if $cn_sort is not empty -- this would be
2924 # an odd combination of events, however
2926 $marc->insert_grouped_field( MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) );
2931 =head2 _koha_add_biblio
2933 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2935 Internal function to add a biblio ($biblio is a hash with the values)
2939 sub _koha_add_biblio {
2940 my ( $dbh, $biblio, $frameworkcode ) = @_;
2944 # set the series flag
2945 unless (defined $biblio->{'serial'}){
2946 $biblio->{'serial'} = 0;
2947 if ( $biblio->{'seriestitle'} ) { $biblio->{'serial'} = 1 }
2950 my $query = "INSERT INTO biblio
2951 SET frameworkcode = ?,
2962 my $sth = $dbh->prepare($query);
2964 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
2965 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}
2968 my $biblionumber = $dbh->{'mysql_insertid'};
2969 if ( $dbh->errstr ) {
2970 $error .= "ERROR in _koha_add_biblio $query" . $dbh->errstr;
2976 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2977 return ( $biblionumber, $error );
2980 =head2 _koha_modify_biblio
2982 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2984 Internal function for updating the biblio table
2988 sub _koha_modify_biblio {
2989 my ( $dbh, $biblio, $frameworkcode ) = @_;
2994 SET frameworkcode = ?,
3003 WHERE biblionumber = ?
3006 my $sth = $dbh->prepare($query);
3009 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
3010 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}, $biblio->{'biblionumber'}
3011 ) if $biblio->{'biblionumber'};
3013 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3014 $error .= "ERROR in _koha_modify_biblio $query" . $dbh->errstr;
3017 return ( $biblio->{'biblionumber'}, $error );
3020 =head2 _koha_modify_biblioitem_nonmarc
3022 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3024 Updates biblioitems row except for marc and marcxml, which should be changed
3029 sub _koha_modify_biblioitem_nonmarc {
3030 my ( $dbh, $biblioitem ) = @_;
3033 # re-calculate the cn_sort, it may have changed
3034 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3036 my $query = "UPDATE biblioitems
3037 SET biblionumber = ?,
3043 publicationyear = ?,
3047 collectiontitle = ?,
3049 collectionvolume= ?,
3050 editionstatement= ?,
3051 editionresponsibility = ?,
3065 where biblioitemnumber = ?
3067 my $sth = $dbh->prepare($query);
3069 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3070 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3071 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3072 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3073 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3074 $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'},
3075 $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'},
3076 $biblioitem->{'biblioitemnumber'}
3078 if ( $dbh->errstr ) {
3079 $error .= "ERROR in _koha_modify_biblioitem_nonmarc $query" . $dbh->errstr;
3082 return ( $biblioitem->{'biblioitemnumber'}, $error );
3085 =head2 _koha_add_biblioitem
3087 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3089 Internal function to add a biblioitem
3093 sub _koha_add_biblioitem {
3094 my ( $dbh, $biblioitem ) = @_;
3097 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3098 my $query = "INSERT INTO biblioitems SET
3105 publicationyear = ?,
3109 collectiontitle = ?,
3111 collectionvolume= ?,
3112 editionstatement= ?,
3113 editionresponsibility = ?,
3129 my $sth = $dbh->prepare($query);
3131 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3132 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3133 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3134 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3135 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3136 $biblioitem->{'lccn'}, $biblioitem->{'marc'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'},
3137 $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort,
3138 $biblioitem->{'totalissues'}
3140 my $bibitemnum = $dbh->{'mysql_insertid'};
3142 if ( $dbh->errstr ) {
3143 $error .= "ERROR in _koha_add_biblioitem $query" . $dbh->errstr;
3147 return ( $bibitemnum, $error );
3150 =head2 _koha_delete_biblio
3152 $error = _koha_delete_biblio($dbh,$biblionumber);
3154 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3156 C<$dbh> - the database handle
3158 C<$biblionumber> - the biblionumber of the biblio to be deleted
3162 # FIXME: add error handling
3164 sub _koha_delete_biblio {
3165 my ( $dbh, $biblionumber ) = @_;
3167 # get all the data for this biblio
3168 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3169 $sth->execute($biblionumber);
3171 if ( my $data = $sth->fetchrow_hashref ) {
3173 # save the record in deletedbiblio
3174 # find the fields to save
3175 my $query = "INSERT INTO deletedbiblio SET ";
3177 foreach my $temp ( keys %$data ) {
3178 $query .= "$temp = ?,";
3179 push( @bind, $data->{$temp} );
3182 # replace the last , by ",?)"
3184 my $bkup_sth = $dbh->prepare($query);
3185 $bkup_sth->execute(@bind);
3189 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3190 $del_sth->execute($biblionumber);
3197 =head2 _koha_delete_biblioitems
3199 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3201 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3203 C<$dbh> - the database handle
3204 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3208 # FIXME: add error handling
3210 sub _koha_delete_biblioitems {
3211 my ( $dbh, $biblioitemnumber ) = @_;
3213 # get all the data for this biblioitem
3214 my $sth = $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3215 $sth->execute($biblioitemnumber);
3217 if ( my $data = $sth->fetchrow_hashref ) {
3219 # save the record in deletedbiblioitems
3220 # find the fields to save
3221 my $query = "INSERT INTO deletedbiblioitems SET ";
3223 foreach my $temp ( keys %$data ) {
3224 $query .= "$temp = ?,";
3225 push( @bind, $data->{$temp} );
3228 # replace the last , by ",?)"
3230 my $bkup_sth = $dbh->prepare($query);
3231 $bkup_sth->execute(@bind);
3234 # delete the biblioitem
3235 my $del_sth = $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3236 $del_sth->execute($biblioitemnumber);
3243 =head1 UNEXPORTED FUNCTIONS
3245 =head2 ModBiblioMarc
3247 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3249 Add MARC data for a biblio to koha
3251 Function exported, but should NOT be used, unless you really know what you're doing
3257 # pass the MARC::Record to this function, and it will create the records in the marc field
3258 my ( $record, $biblionumber, $frameworkcode ) = @_;
3259 my $dbh = C4::Context->dbh;
3260 my @fields = $record->fields();
3261 if ( !$frameworkcode ) {
3262 $frameworkcode = "";
3264 my $sth = $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3265 $sth->execute( $frameworkcode, $biblionumber );
3267 my $encoding = C4::Context->preference("marcflavour");
3269 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3270 if ( $encoding eq "UNIMARC" ) {
3271 my $string = $record->subfield( 100, "a" );
3272 if ( ($string) && ( length( $record->subfield( 100, "a" ) ) == 36 ) ) {
3273 my $f100 = $record->field(100);
3274 $record->delete_field($f100);
3276 $string = POSIX::strftime( "%Y%m%d", localtime );
3278 $string = sprintf( "%-*s", 35, $string );
3280 substr( $string, 22, 6, "frey50" );
3281 unless ( $record->subfield( 100, "a" ) ) {
3282 $record->insert_grouped_field( MARC::Field->new( 100, "", "", "a" => $string ) );
3286 #enhancement 5374: update transaction date (005) for marc21/unimarc
3287 if($encoding =~ /MARC21|UNIMARC/) {
3288 my @a= (localtime) [5,4,3,2,1,0]; $a[0]+=1900; $a[1]++;
3289 # YY MM DD HH MM SS (update year and month)
3290 my $f005= $record->field('005');
3291 $f005->update(sprintf("%4d%02d%02d%02d%02d%04.1f",@a)) if $f005;
3295 if ( C4::Context->preference("NoZebra") ) {
3297 # only NoZebra indexing needs to have
3298 # the previous version of the record
3299 $oldRecord = GetMarcBiblio($biblionumber);
3301 $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3302 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding), $biblionumber );
3304 ModZebra( $biblionumber, "specialUpdate", "biblioserver", $oldRecord, $record );
3305 return $biblionumber;
3308 =head2 z3950_extended_services
3310 z3950_extended_services($serviceType,$serviceOptions,$record);
3312 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.
3314 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3316 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3318 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3322 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3323 syntax => the record syntax (transfer syntax)
3324 databaseName = Database from connection object
3326 To set serviceOptions, call set_service_options($serviceType)
3328 C<$record> the record, if one is needed for the service type
3330 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3334 sub z3950_extended_services {
3335 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3337 # get our connection object
3338 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3340 # create a new package object
3341 my $Zpackage = $Zconn->package();
3344 $Zpackage->option( action => $action );
3346 if ( $serviceOptions->{'databaseName'} ) {
3347 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3349 if ( $serviceOptions->{'recordIdNumber'} ) {
3350 $Zpackage->option( recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3352 if ( $serviceOptions->{'recordIdOpaque'} ) {
3353 $Zpackage->option( recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3356 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3357 #if ($serviceType eq 'itemorder') {
3358 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3359 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3360 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3361 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3364 if ( $serviceOptions->{record} ) {
3365 $Zpackage->option( record => $serviceOptions->{record} );
3367 # can be xml or marc
3368 if ( $serviceOptions->{'syntax'} ) {
3369 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3373 # send the request, handle any exception encountered
3374 eval { $Zpackage->send($serviceType) };
3375 if ( $@ && $@->isa("ZOOM::Exception") ) {
3376 return "error: " . $@->code() . " " . $@->message() . "\n";
3379 # free up package resources
3380 $Zpackage->destroy();
3383 =head2 set_service_options
3385 my $serviceOptions = set_service_options($serviceType);
3387 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3389 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3393 sub set_service_options {
3394 my ($serviceType) = @_;
3397 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3398 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3400 if ( $serviceType eq 'commit' ) {
3404 if ( $serviceType eq 'create' ) {
3408 if ( $serviceType eq 'drop' ) {
3409 die "ERROR: 'drop' not currently supported (by Zebra)";
3411 return $serviceOptions;
3414 =head2 get_biblio_authorised_values
3416 find the types and values for all authorised values assigned to this biblio.
3420 MARC::Record of the bib
3422 returns: a hashref mapping the authorised value to the value set for this biblionumber
3424 $authorised_values = {
3425 'Scent' => 'flowery',
3426 'Audience' => 'Young Adult',
3427 'itemtypes' => 'SER',
3430 Notes: forlibrarian should probably be passed in, and called something different.
3434 sub get_biblio_authorised_values {
3435 my $biblionumber = shift;
3438 my $forlibrarian = 1; # are we in staff or opac?
3439 my $frameworkcode = GetFrameworkCode($biblionumber);
3441 my $authorised_values;
3443 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3444 or return $authorised_values;
3446 # assume that these entries in the authorised_value table are bibliolevel.
3447 # ones that start with 'item%' are item level.
3448 my $query = q(SELECT distinct authorised_value, kohafield
3449 FROM marc_subfield_structure
3450 WHERE authorised_value !=''
3451 AND (kohafield like 'biblio%'
3452 OR kohafield like '') );
3453 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3455 foreach my $tag ( keys(%$tagslib) ) {
3456 foreach my $subfield ( keys( %{ $tagslib->{$tag} } ) ) {
3458 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3459 if ( 'HASH' eq ref $tagslib->{$tag}{$subfield} ) {
3460 if ( defined $tagslib->{$tag}{$subfield}{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } ) {
3461 if ( defined $record->field($tag) ) {
3462 my $this_subfield_value = $record->field($tag)->subfield($subfield);
3463 if ( defined $this_subfield_value ) {
3464 $authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } = $this_subfield_value;
3472 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3473 return $authorised_values;
3482 Koha Development Team <http://koha-community.org/>
3484 Paul POULAIN paul.poulain@free.fr
3486 Joshua Ferraro jmf@liblime.com