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
103 # To link headings in a bib record
104 # to authority records.
106 &LinkBibHeadingsToAuthorities
110 # those functions are exported but should not be used
111 # they are usefull is few circumstances, so are exported.
112 # but don't use them unless you're a core developer ;-)
120 &TransformHtmlToMarc2
123 &PrepareItemrecordDisplay
129 my $servers = C4::Context->config('memcached_servers');
131 require Memoize::Memcached;
132 import Memoize::Memcached qw(memoize_memcached);
135 servers => [$servers],
136 key_prefix => C4::Context->config('memcached_namespace') || 'koha',
138 memoize_memcached( 'GetMarcStructure', memcached => $memcached, expire_time => 600 ); #cache for 10 minutes
144 C4::Biblio - cataloging management functions
148 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:
152 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
154 =item 2. as raw MARC in the Zebra index and storage engine
156 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
160 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
162 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.
166 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
168 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
172 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:
176 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
178 =item 2. _koha_* - low-level internal functions for managing the koha tables
180 =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.
182 =item 4. Zebra functions used to update the Zebra index
184 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
188 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 :
192 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
194 =item 2. add the biblionumber and biblioitemnumber into the MARC records
196 =item 3. save the marc record
200 When dealing with items, we must :
204 =item 1. save the item in items table, that gives us an itemnumber
206 =item 2. add the itemnumber to the item MARC field
208 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
210 When modifying a biblio or an item, the behaviour is quite similar.
214 =head1 EXPORTED FUNCTIONS
218 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
220 Exported function (core API) for adding a new biblio to koha.
222 The first argument is a C<MARC::Record> object containing the
223 bib to add, while the second argument is the desired MARC
226 This function also accepts a third, optional argument: a hashref
227 to additional options. The only defined option is C<defer_marc_save>,
228 which if present and mapped to a true value, causes C<AddBiblio>
229 to omit the call to save the MARC in C<bibilioitems.marc>
230 and C<biblioitems.marcxml> This option is provided B<only>
231 for the use of scripts such as C<bulkmarcimport.pl> that may need
232 to do some manipulation of the MARC record for item parsing before
233 saving it and which cannot afford the performance hit of saving
234 the MARC record twice. Consequently, do not use that option
235 unless you can guarantee that C<ModBiblioMarc> will be called.
241 my $frameworkcode = shift;
242 my $options = @_ ? shift : undef;
243 my $defer_marc_save = 0;
244 if ( defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'} ) {
245 $defer_marc_save = 1;
248 my ( $biblionumber, $biblioitemnumber, $error );
249 my $dbh = C4::Context->dbh;
251 # transform the data into koha-table style data
252 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
253 ( $biblionumber, $error ) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
254 $olddata->{'biblionumber'} = $biblionumber;
255 ( $biblioitemnumber, $error ) = _koha_add_biblioitem( $dbh, $olddata );
257 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
259 # update MARC subfield that stores biblioitems.cn_sort
260 _koha_marc_update_biblioitem_cn_sort( $record, $olddata, $frameworkcode );
263 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
265 logaction( "CATALOGUING", "ADD", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
266 return ( $biblionumber, $biblioitemnumber );
271 ModBiblio( $record,$biblionumber,$frameworkcode);
273 Replace an existing bib record identified by C<$biblionumber>
274 with one supplied by the MARC::Record object C<$record>. The embedded
275 item, biblioitem, and biblionumber fields from the previous
276 version of the bib record replace any such fields of those tags that
277 are present in C<$record>. Consequently, ModBiblio() is not
278 to be used to try to modify item records.
280 C<$frameworkcode> specifies the MARC framework to use
281 when storing the modified bib record; among other things,
282 this controls how MARC fields get mapped to display columns
283 in the C<biblio> and C<biblioitems> tables, as well as
284 which fields are used to store embedded item, biblioitem,
285 and biblionumber data for indexing.
290 my ( $record, $biblionumber, $frameworkcode ) = @_;
291 if ( C4::Context->preference("CataloguingLog") ) {
292 my $newrecord = GetMarcBiblio($biblionumber);
293 logaction( "CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>" . $newrecord->as_formatted );
296 my $dbh = C4::Context->dbh;
298 $frameworkcode = "" unless $frameworkcode;
300 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
301 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
302 my $oldRecord = GetMarcBiblio($biblionumber);
304 # delete any item fields from incoming record to avoid
305 # duplication or incorrect data - use AddItem() or ModItem()
307 foreach my $field ( $record->field($itemtag) ) {
308 $record->delete_field($field);
311 # parse each item, and, for an unknown reason, re-encode each subfield
312 # if you don't do that, the record will have encoding mixed
313 # and the biblio will be re-encoded.
314 # strange, I (Paul P.) searched more than 1 day to understand what happends
315 # but could only solve the problem this way...
316 my @fields = $oldRecord->field($itemtag);
317 foreach my $fielditem (@fields) {
319 foreach ( $fielditem->subfields() ) {
321 $field->add_subfields( Encode::encode( 'utf-8', $_->[0] ) => Encode::encode( 'utf-8', $_->[1] ) );
323 $field = MARC::Field->new( "$itemtag", '', '', Encode::encode( 'utf-8', $_->[0] ) => Encode::encode( 'utf-8', $_->[1] ) );
326 $record->append_fields($field);
329 foreach my $field ($record->fields()) {
330 if (! $field->is_control_field()) {
331 if (scalar($field->subfields()) == 0) {
332 $record->delete_fields($field);
337 # update biblionumber and biblioitemnumber in MARC
338 # FIXME - this is assuming a 1 to 1 relationship between
339 # biblios and biblioitems
340 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
341 $sth->execute($biblionumber);
342 my ($biblioitemnumber) = $sth->fetchrow;
344 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
346 # load the koha-table data object
347 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
349 # update MARC subfield that stores biblioitems.cn_sort
350 _koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode );
352 # update the MARC record (that now contains biblio and items) with the new record data
353 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
355 # modify the other koha tables
356 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
357 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
361 =head2 ModBiblioframework
363 ModBiblioframework($biblionumber,$frameworkcode);
365 Exported function to modify a biblio framework
369 sub ModBiblioframework {
370 my ( $biblionumber, $frameworkcode ) = @_;
371 my $dbh = C4::Context->dbh;
372 my $sth = $dbh->prepare( "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?" );
373 $sth->execute( $frameworkcode, $biblionumber );
379 my $error = &DelBiblio($dbh,$biblionumber);
381 Exported function (core API) for deleting a biblio in koha.
382 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
383 Also backs it up to deleted* tables
384 Checks to make sure there are not issues on any of the items
386 C<$error> : undef unless an error occurs
391 my ($biblionumber) = @_;
392 my $dbh = C4::Context->dbh;
393 my $error; # for error handling
395 # First make sure this biblio has no items attached
396 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
397 $sth->execute($biblionumber);
398 if ( my $itemnumber = $sth->fetchrow ) {
400 # Fix this to use a status the template can understand
401 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
404 return $error if $error;
406 # We delete attached subscriptions
407 my $subscriptions = &C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
408 foreach my $subscription (@$subscriptions) {
409 &C4::Serials::DelSubscription( $subscription->{subscriptionid} );
412 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
413 # for at least 2 reasons :
414 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
415 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
416 # 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)
418 if ( C4::Context->preference("NoZebra") ) {
420 # only NoZebra indexing needs to have
421 # the previous version of the record
422 $oldRecord = GetMarcBiblio($biblionumber);
424 ModZebra( $biblionumber, "recordDelete", "biblioserver", $oldRecord, undef );
426 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
427 $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
428 $sth->execute($biblionumber);
429 while ( my $biblioitemnumber = $sth->fetchrow ) {
431 # delete this biblioitem
432 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
433 return $error if $error;
436 # delete biblio from Koha tables and save in deletedbiblio
437 # must do this *after* _koha_delete_biblioitems, otherwise
438 # delete cascade will prevent deletedbiblioitems rows
439 # from being generated by _koha_delete_biblioitems
440 $error = _koha_delete_biblio( $dbh, $biblionumber );
442 logaction( "CATALOGUING", "DELETE", $biblionumber, "" ) if C4::Context->preference("CataloguingLog");
447 =head2 LinkBibHeadingsToAuthorities
449 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
451 Links bib headings to authority records by checking
452 each authority-controlled field in the C<MARC::Record>
453 object C<$marc>, looking for a matching authority record,
454 and setting the linking subfield $9 to the ID of that
457 If no matching authority exists, or if multiple
458 authorities match, no $9 will be added, and any
459 existing one inthe field will be deleted.
461 Returns the number of heading links changed in the
466 sub LinkBibHeadingsToAuthorities {
469 my $num_headings_changed = 0;
470 foreach my $field ( $bib->fields() ) {
471 my $heading = C4::Heading->new_from_bib_field($field);
472 next unless defined $heading;
475 my $current_link = $field->subfield('9');
477 # look for matching authorities
478 my $authorities = $heading->authorities();
480 # want only one exact match
481 if ( $#{$authorities} == 0 ) {
482 my $authority = MARC::Record->new_from_usmarc( $authorities->[0] );
483 my $authid = $authority->field('001')->data();
484 next if defined $current_link and $current_link eq $authid;
486 $field->delete_subfield( code => '9' ) if defined $current_link;
487 $field->add_subfields( '9', $authid );
488 $num_headings_changed++;
490 if ( defined $current_link ) {
491 $field->delete_subfield( code => '9' );
492 $num_headings_changed++;
497 return $num_headings_changed;
500 =head2 GetRecordValue
502 my $values = GetRecordValue($field, $record, $frameworkcode);
504 Get MARC fields from a keyword defined in fieldmapping table.
509 my ( $field, $record, $frameworkcode ) = @_;
510 my $dbh = C4::Context->dbh;
512 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
513 $sth->execute( $frameworkcode, $field );
517 while ( my $row = $sth->fetchrow_hashref ) {
518 foreach my $field ( $record->field( $row->{fieldcode} ) ) {
519 if ( ( $row->{subfieldcode} ne "" && $field->subfield( $row->{subfieldcode} ) ) ) {
520 foreach my $subfield ( $field->subfield( $row->{subfieldcode} ) ) {
521 push @result, { 'subfield' => $subfield };
524 } elsif ( $row->{subfieldcode} eq "" ) {
525 push @result, { 'subfield' => $field->as_string() };
533 =head2 SetFieldMapping
535 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
537 Set a Field to MARC mapping value, if it already exists we don't add a new one.
541 sub SetFieldMapping {
542 my ( $framework, $field, $fieldcode, $subfieldcode ) = @_;
543 my $dbh = C4::Context->dbh;
545 my $sth = $dbh->prepare('SELECT * FROM fieldmapping WHERE fieldcode = ? AND subfieldcode = ? AND frameworkcode = ? AND field = ?');
546 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
547 if ( not $sth->fetchrow_hashref ) {
549 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
551 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
555 =head2 DeleteFieldMapping
557 DeleteFieldMapping($id);
559 Delete a field mapping from an $id.
563 sub DeleteFieldMapping {
565 my $dbh = C4::Context->dbh;
567 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
571 =head2 GetFieldMapping
573 GetFieldMapping($frameworkcode);
575 Get all field mappings for a specified frameworkcode
579 sub GetFieldMapping {
580 my ($framework) = @_;
581 my $dbh = C4::Context->dbh;
583 my $sth = $dbh->prepare('SELECT * FROM fieldmapping where frameworkcode = ?');
584 $sth->execute($framework);
587 while ( my $row = $sth->fetchrow_hashref ) {
595 $data = &GetBiblioData($biblionumber);
597 Returns information about the book with the given biblionumber.
598 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
599 the C<biblio> and C<biblioitems> tables in the
602 In addition, C<$data-E<gt>{subject}> is the list of the book's
603 subjects, separated by C<" , "> (space, comma, space).
604 If there are multiple biblioitems with the given biblionumber, only
605 the first one is considered.
611 my $dbh = C4::Context->dbh;
613 # my $query = C4::Context->preference('item-level_itypes') ?
614 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
616 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
617 # WHERE biblio.biblionumber = ?
618 # AND biblioitems.biblionumber = biblio.biblionumber
621 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
623 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
624 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
625 WHERE biblio.biblionumber = ?
626 AND biblioitems.biblionumber = biblio.biblionumber ";
628 my $sth = $dbh->prepare($query);
629 $sth->execute($bibnum);
631 $data = $sth->fetchrow_hashref;
635 } # sub GetBiblioData
637 =head2 &GetBiblioItemData
639 $itemdata = &GetBiblioItemData($biblioitemnumber);
641 Looks up the biblioitem with the given biblioitemnumber. Returns a
642 reference-to-hash. The keys are the fields from the C<biblio>,
643 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
644 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
649 sub GetBiblioItemData {
650 my ($biblioitemnumber) = @_;
651 my $dbh = C4::Context->dbh;
652 my $query = "SELECT *,biblioitems.notes AS bnotes
653 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
654 unless ( C4::Context->preference('item-level_itypes') ) {
655 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
657 $query .= " WHERE biblioitemnumber = ? ";
658 my $sth = $dbh->prepare($query);
660 $sth->execute($biblioitemnumber);
661 $data = $sth->fetchrow_hashref;
664 } # sub &GetBiblioItemData
666 =head2 GetBiblioItemByBiblioNumber
668 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
672 sub GetBiblioItemByBiblioNumber {
673 my ($biblionumber) = @_;
674 my $dbh = C4::Context->dbh;
675 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
679 $sth->execute($biblionumber);
681 while ( my $data = $sth->fetchrow_hashref ) {
682 push @results, $data;
689 =head2 GetBiblionumberFromItemnumber
694 sub GetBiblionumberFromItemnumber {
695 my ($itemnumber) = @_;
696 my $dbh = C4::Context->dbh;
697 my $sth = $dbh->prepare("Select biblionumber FROM items WHERE itemnumber = ?");
699 $sth->execute($itemnumber);
700 my ($result) = $sth->fetchrow;
704 =head2 GetBiblioFromItemNumber
706 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
708 Looks up the item with the given itemnumber. if undef, try the barcode.
710 C<&itemnodata> returns a reference-to-hash whose keys are the fields
711 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
717 sub GetBiblioFromItemNumber {
718 my ( $itemnumber, $barcode ) = @_;
719 my $dbh = C4::Context->dbh;
722 $sth = $dbh->prepare(
724 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
725 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
726 WHERE items.itemnumber = ?"
728 $sth->execute($itemnumber);
730 $sth = $dbh->prepare(
732 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
733 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
734 WHERE items.barcode = ?"
736 $sth->execute($barcode);
738 my $data = $sth->fetchrow_hashref;
745 $isbd = &GetISBDView($biblionumber);
747 Return the ISBD view which can be included in opac and intranet
752 my ( $biblionumber, $template ) = @_;
753 my $record = GetMarcBiblio($biblionumber);
754 my $itemtype = &GetFrameworkCode($biblionumber);
755 my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch", $itemtype );
756 my $tagslib = &GetMarcStructure( 1, $itemtype );
758 my $ISBD = C4::Context->preference('ISBD');
763 foreach my $isbdfield ( split( /#/, $bloc ) ) {
765 # $isbdfield= /(.?.?.?)/;
766 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
767 my $fieldvalue = $1 || 0;
768 my $subfvalue = $2 || "";
770 my $analysestring = $4;
773 # warn "==> $1 / $2 / $3 / $4";
774 # my $fieldvalue=substr($isbdfield,0,3);
775 if ( $fieldvalue > 0 ) {
776 my $hasputtextbefore = 0;
777 my @fieldslist = $record->field($fieldvalue);
778 @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf );
780 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
781 # warn "FV : $fieldvalue";
782 if ( $subfvalue ne "" ) {
783 foreach my $field (@fieldslist) {
784 foreach my $subfield ( $field->subfield($subfvalue) ) {
785 my $calculated = $analysestring;
786 my $tag = $field->tag();
789 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib );
790 my $tagsubf = $tag . $subfvalue;
791 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
792 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
794 # field builded, store the result
795 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
796 $blocres .= $textbefore;
797 $hasputtextbefore = 1;
800 # remove punctuation at start
801 $calculated =~ s/^( |;|:|\.|-)*//g;
802 $blocres .= $calculated;
807 $blocres .= $textafter if $hasputtextbefore;
809 foreach my $field (@fieldslist) {
810 my $calculated = $analysestring;
811 my $tag = $field->tag();
814 my @subf = $field->subfields;
815 for my $i ( 0 .. $#subf ) {
816 my $valuecode = $subf[$i][1];
817 my $subfieldcode = $subf[$i][0];
818 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib );
819 my $tagsubf = $tag . $subfieldcode;
821 $calculated =~ s/ # replace all {{}} codes by the value code.
822 \{\{$tagsubf\}\} # catch the {{actualcode}}
824 $valuecode # replace by the value code
827 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
828 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
831 # field builded, store the result
832 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
833 $blocres .= $textbefore;
834 $hasputtextbefore = 1;
837 # remove punctuation at start
838 $calculated =~ s/^( |;|:|\.|-)*//g;
839 $blocres .= $calculated;
842 $blocres .= $textafter if $hasputtextbefore;
845 $blocres .= $isbdfield;
850 $res =~ s/\{(.*?)\}//g;
852 $res =~ s/\n/<br\/>/g;
862 ( $count, @results ) = &GetBiblio($biblionumber);
867 my ($biblionumber) = @_;
868 my $dbh = C4::Context->dbh;
869 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
872 $sth->execute($biblionumber);
873 while ( my $data = $sth->fetchrow_hashref ) {
874 $results[$count] = $data;
878 return ( $count, @results );
881 =head2 GetBiblioItemInfosOf
883 GetBiblioItemInfosOf(@biblioitemnumbers);
887 sub GetBiblioItemInfosOf {
888 my @biblioitemnumbers = @_;
891 SELECT biblioitemnumber,
895 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
897 return get_infos_of( $query, 'biblioitemnumber' );
900 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
902 =head2 GetMarcStructure
904 $res = GetMarcStructure($forlibrarian,$frameworkcode);
906 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
907 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
908 $frameworkcode : the framework code to read
912 # cache for results of GetMarcStructure -- needed
914 our $marc_structure_cache;
916 sub GetMarcStructure {
917 my ( $forlibrarian, $frameworkcode ) = @_;
918 my $dbh = C4::Context->dbh;
919 $frameworkcode = "" unless $frameworkcode;
921 if ( defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode} ) {
922 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
925 # my $sth = $dbh->prepare(
926 # "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
927 # $sth->execute($frameworkcode);
928 # my ($total) = $sth->fetchrow;
929 # $frameworkcode = "" unless ( $total > 0 );
930 my $sth = $dbh->prepare(
931 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
932 FROM marc_tag_structure
933 WHERE frameworkcode=?
936 $sth->execute($frameworkcode);
937 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
939 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
940 $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
941 $res->{$tag}->{tab} = "";
942 $res->{$tag}->{mandatory} = $mandatory;
943 $res->{$tag}->{repeatable} = $repeatable;
946 $sth = $dbh->prepare(
947 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
948 FROM marc_subfield_structure
949 WHERE frameworkcode=?
950 ORDER BY tagfield,tagsubfield
954 $sth->execute($frameworkcode);
957 my $authorised_value;
968 ( $tag, $subfield, $liblibrarian, $libopac, $tab, $mandatory, $repeatable, $authorised_value,
969 $authtypecode, $value_builder, $kohafield, $seealso, $hidden, $isurl, $link, $defaultvalue
973 $res->{$tag}->{$subfield}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
974 $res->{$tag}->{$subfield}->{tab} = $tab;
975 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
976 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
977 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
978 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
979 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
980 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
981 $res->{$tag}->{$subfield}->{seealso} = $seealso;
982 $res->{$tag}->{$subfield}->{hidden} = $hidden;
983 $res->{$tag}->{$subfield}->{isurl} = $isurl;
984 $res->{$tag}->{$subfield}->{'link'} = $link;
985 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
988 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
993 =head2 GetUsedMarcStructure
995 The same function as GetMarcStructure except it just takes field
996 in tab 0-9. (used field)
998 my $results = GetUsedMarcStructure($frameworkcode);
1000 C<$results> is a ref to an array which each case containts a ref
1001 to a hash which each keys is the columns from marc_subfield_structure
1003 C<$frameworkcode> is the framework code.
1007 sub GetUsedMarcStructure($) {
1008 my $frameworkcode = shift || '';
1011 FROM marc_subfield_structure
1013 AND frameworkcode = ?
1014 ORDER BY tagfield, tagsubfield
1016 my $sth = C4::Context->dbh->prepare($query);
1017 $sth->execute($frameworkcode);
1018 return $sth->fetchall_arrayref( {} );
1021 =head2 GetMarcFromKohaField
1023 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1025 Returns the MARC fields & subfields mapped to the koha field
1026 for the given frameworkcode
1030 sub GetMarcFromKohaField {
1031 my ( $kohafield, $frameworkcode ) = @_;
1032 return 0, 0 unless $kohafield and defined $frameworkcode;
1033 my $relations = C4::Context->marcfromkohafield;
1034 return ( $relations->{$frameworkcode}->{$kohafield}->[0], $relations->{$frameworkcode}->{$kohafield}->[1] );
1037 =head2 GetMarcBiblio
1039 my $record = GetMarcBiblio($biblionumber);
1041 Returns MARC::Record representing bib identified by
1042 C<$biblionumber>. If no bib exists, returns undef.
1043 The MARC record contains both biblio & item data.
1048 my $biblionumber = shift;
1049 my $dbh = C4::Context->dbh;
1050 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1051 $sth->execute($biblionumber);
1052 my $row = $sth->fetchrow_hashref;
1053 my $marcxml = StripNonXmlChars( $row->{'marcxml'} );
1054 MARC::File::XML->default_record_format( C4::Context->preference('marcflavour') );
1055 my $record = MARC::Record->new();
1058 $record = eval { MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour') ) };
1059 if ($@) { warn " problem with :$biblionumber : $@ \n$marcxml"; }
1061 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1070 my $marcxml = GetXmlBiblio($biblionumber);
1072 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1073 The XML contains both biblio & item datas
1078 my ($biblionumber) = @_;
1079 my $dbh = C4::Context->dbh;
1080 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1081 $sth->execute($biblionumber);
1082 my ($marcxml) = $sth->fetchrow;
1086 =head2 GetCOinSBiblio
1088 my $coins = GetCOinSBiblio($biblionumber);
1090 Returns the COinS(a span) which can be included in a biblio record
1094 sub GetCOinSBiblio {
1095 my ($biblionumber) = @_;
1096 my $record = GetMarcBiblio($biblionumber);
1098 # get the coin format
1100 # can't get a valid MARC::Record object, bail out at this point
1101 warn "We called GetMarcBiblio with a biblionumber that doesn't exist biblionumber=$biblionumber";
1104 my $pos7 = substr $record->leader(), 7, 1;
1105 my $pos6 = substr $record->leader(), 6, 1;
1108 my ( $aulast, $aufirst ) = ( '', '' );
1117 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
1122 'b' => 'manuscript',
1124 'd' => 'manuscript',
1128 'i' => 'audioRecording',
1129 'j' => 'audioRecording',
1132 'm' => 'computerProgram',
1137 'a' => 'journalArticle',
1141 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
1143 if ( $genre eq 'book' ) {
1144 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1147 ##### We must transform mtx to a valable mtx and document type ####
1148 if ( $genre eq 'book' ) {
1150 } elsif ( $genre eq 'journal' ) {
1152 } elsif ( $genre eq 'journalArticle' ) {
1159 $genre = ( $mtx eq 'dc' ) ? "&rft.type=$genre" : "&rft.genre=$genre";
1162 $aulast = $record->subfield( '700', 'a' );
1163 $aufirst = $record->subfield( '700', 'b' );
1164 $oauthors = "&rft.au=$aufirst $aulast";
1167 if ( $record->field('200') ) {
1168 for my $au ( $record->field('200')->subfield('g') ) {
1169 $oauthors .= "&rft.au=$au";
1174 ? "&rft.title=" . $record->subfield( '200', 'a' )
1175 : "&rft.title=" . $record->subfield( '200', 'a' ) . "&rft.btitle=" . $record->subfield( '200', 'a' );
1176 $pubyear = $record->subfield( '210', 'd' );
1177 $publisher = $record->subfield( '210', 'c' );
1178 $isbn = $record->subfield( '010', 'a' );
1179 $issn = $record->subfield( '011', 'a' );
1182 # MARC21 need some improve
1185 $genre = "&rft.genre=book";
1188 if ( $record->field('100') ) {
1189 $oauthors .= "&rft.au=" . $record->subfield( '100', 'a' );
1193 if ( $record->field('700') ) {
1194 for my $au ( $record->field('700')->subfield('a') ) {
1195 $oauthors .= "&rft.au=$au";
1198 $title = "&rft.btitle=" . $record->subfield( '245', 'a' );
1199 $subtitle = $record->subfield( '245', 'b' ) || '';
1200 $title .= $subtitle;
1201 $pubyear = $record->subfield( '260', 'c' ) || '';
1202 $publisher = $record->subfield( '260', 'b' ) || '';
1203 $isbn = $record->subfield( '020', 'a' ) || '';
1204 $issn = $record->subfield( '022', 'a' ) || '';
1208 "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";
1209 $coins_value =~ s/(\ |&[^a])/\+/g;
1210 $coins_value =~ s/\"/\"\;/g;
1212 #<!-- 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="
1214 return $coins_value;
1217 =head2 GetAuthorisedValueDesc
1219 my $subfieldvalue =get_authorised_value_desc(
1220 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category, $opac);
1222 Retrieve the complete description for a given authorised value.
1224 Now takes $category and $value pair too.
1226 my $auth_value_desc =GetAuthorisedValueDesc(
1227 '','', 'DVD' ,'','','CCODE');
1229 If the optional $opac parameter is set to a true value, displays OPAC
1230 descriptions rather than normal ones when they exist.
1234 sub GetAuthorisedValueDesc {
1235 my ( $tag, $subfield, $value, $framework, $tagslib, $category, $opac ) = @_;
1236 my $dbh = C4::Context->dbh;
1240 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1243 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1244 return C4::Branch::GetBranchName($value);
1248 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1249 return getitemtypeinfo($value)->{description};
1252 #---- "true" authorized value
1253 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1256 if ( $category ne "" ) {
1257 my $sth = $dbh->prepare( "SELECT lib, lib_opac FROM authorised_values WHERE category = ? AND authorised_value = ?" );
1258 $sth->execute( $category, $value );
1259 my $data = $sth->fetchrow_hashref;
1260 return ( $opac && $data->{'lib_opac'} ) ? $data->{'lib_opac'} : $data->{'lib'};
1262 return $value; # if nothing is found return the original value
1266 =head2 GetMarcControlnumber
1268 $marccontrolnumber = GetMarcControlnumber($record,$marcflavour);
1270 Get the control number / record Identifier from the MARC record and return it.
1274 sub GetMarcControlnumber {
1275 my ( $record, $marcflavour ) = @_;
1276 my $controlnumber = "";
1277 # Control number or Record identifier are the same field in MARC21 and UNIMARC
1278 # Keep $marcflavour for possible later use
1279 if ($marcflavour eq "MARC21" || $marcflavour eq "UNIMARC") {
1280 my $controlnumberField = $record->field('001');
1281 if ($controlnumberField) {
1282 $controlnumber = $controlnumberField->data();
1285 return $controlnumber;
1290 $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
1292 Get all ISBNs from the MARC record and returns them in an array.
1293 ISBNs stored in differents places depending on MARC flavour
1298 my ( $record, $marcflavour ) = @_;
1300 if ( $marcflavour eq "MARC21" ) {
1302 } else { # assume unimarc if not marc21
1309 foreach my $field ( $record->field($scope) ) {
1310 my $value = $field->as_string();
1311 if ( $isbn ne "" ) {
1312 $marcisbn = { marcisbn => $isbn, };
1313 push @marcisbns, $marcisbn;
1316 if ( $isbn ne $value ) {
1317 $isbn = $isbn . " " . $value;
1322 $marcisbn = { marcisbn => $isbn };
1323 push @marcisbns, $marcisbn; #load last tag into array
1330 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1332 Get all notes from the MARC record and returns them in an array.
1333 The note are stored in differents places depending on MARC flavour
1338 my ( $record, $marcflavour ) = @_;
1340 if ( $marcflavour eq "MARC21" ) {
1342 } else { # assume unimarc if not marc21
1349 foreach my $field ( $record->field($scope) ) {
1350 my $value = $field->as_string();
1351 if ( $note ne "" ) {
1352 $marcnote = { marcnote => $note, };
1353 push @marcnotes, $marcnote;
1356 if ( $note ne $value ) {
1357 $note = $note . " " . $value;
1362 $marcnote = { marcnote => $note };
1363 push @marcnotes, $marcnote; #load last tag into array
1366 } # end GetMarcNotes
1368 =head2 GetMarcSubjects
1370 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1372 Get all subjects from the MARC record and returns them in an array.
1373 The subjects are stored in differents places depending on MARC flavour
1377 sub GetMarcSubjects {
1378 my ( $record, $marcflavour ) = @_;
1379 my ( $mintag, $maxtag );
1380 if ( $marcflavour eq "MARC21" ) {
1383 } else { # assume unimarc if not marc21
1393 foreach my $field ( $record->field('6..') ) {
1394 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1396 my @subfields = $field->subfields();
1400 # if there is an authority link, build the link with an= subfield9
1402 for my $subject_subfield (@subfields) {
1404 # don't load unimarc subfields 3,4,5
1405 next if ( ( $marcflavour eq "UNIMARC" ) and ( $subject_subfield->[0] =~ /2|3|4|5/ ) );
1407 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1408 next if ( ( $marcflavour eq "MARC21" ) and ( $subject_subfield->[0] =~ /2/ ) );
1409 my $code = $subject_subfield->[0];
1410 my $value = $subject_subfield->[1];
1411 my $linkvalue = $value;
1412 $linkvalue =~ s/(\(|\))//g;
1413 my $operator = " and " unless $counter == 0;
1416 @link_loop = ( { 'limit' => 'an', link => "$linkvalue" } );
1418 if ( not $found9 ) {
1419 push @link_loop, { 'limit' => 'su', link => $linkvalue, operator => $operator };
1421 my $separator = C4::Context->preference("authoritysep") unless $counter == 0;
1424 my @this_link_loop = @link_loop;
1425 push @subfields_loop, { code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator } unless ( $subject_subfield->[0] eq 9 );
1429 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1432 return \@marcsubjects;
1433 } #end getMARCsubjects
1435 =head2 GetMarcAuthors
1437 authors = GetMarcAuthors($record,$marcflavour);
1439 Get all authors from the MARC record and returns them in an array.
1440 The authors are stored in differents places depending on MARC flavour
1444 sub GetMarcAuthors {
1445 my ( $record, $marcflavour ) = @_;
1446 my ( $mintag, $maxtag );
1448 # tagslib useful for UNIMARC author reponsabilities
1450 &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.
1451 if ( $marcflavour eq "MARC21" ) {
1454 } elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1462 foreach my $field ( $record->fields ) {
1463 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1466 my @subfields = $field->subfields();
1469 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1470 my $subfield9 = $field->subfield('9');
1471 for my $authors_subfield (@subfields) {
1473 # don't load unimarc subfields 3, 5
1474 next if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /3|5/ ) );
1475 my $subfieldcode = $authors_subfield->[0];
1476 my $value = $authors_subfield->[1];
1477 my $linkvalue = $value;
1478 $linkvalue =~ s/(\(|\))//g;
1479 my $operator = " and " unless $count_auth == 0;
1481 # if we have an authority link, use that as the link, otherwise use standard searching
1483 @link_loop = ( { 'limit' => 'an', link => "$subfield9" } );
1486 # reset $linkvalue if UNIMARC author responsibility
1487 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] eq "4" ) ) {
1488 $linkvalue = "(" . GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) . ")";
1490 push @link_loop, { 'limit' => 'au', link => $linkvalue, operator => $operator };
1492 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib )
1493 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /4/ ) );
1494 my @this_link_loop = @link_loop;
1495 my $separator = C4::Context->preference("authoritysep") unless $count_auth == 0;
1496 push @subfields_loop, { code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator } unless ( $authors_subfield->[0] eq '9' );
1499 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1501 return \@marcauthors;
1506 $marcurls = GetMarcUrls($record,$marcflavour);
1508 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1509 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1514 my ( $record, $marcflavour ) = @_;
1517 for my $field ( $record->field('856') ) {
1519 for my $note ( $field->subfield('z') ) {
1520 push @notes, { note => $note };
1522 my @urls = $field->subfield('u');
1523 foreach my $url (@urls) {
1525 if ( $marcflavour eq 'MARC21' ) {
1526 my $s3 = $field->subfield('3');
1527 my $link = $field->subfield('y');
1528 unless ( $url =~ /^\w+:/ ) {
1529 if ( $field->indicator(1) eq '7' ) {
1530 $url = $field->subfield('2') . "://" . $url;
1531 } elsif ( $field->indicator(1) eq '1' ) {
1532 $url = 'ftp://' . $url;
1535 # properly, this should be if ind1=4,
1536 # however we will assume http protocol since we're building a link.
1537 $url = 'http://' . $url;
1541 # TODO handle ind 2 (relationship)
1546 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1547 $marcurl->{'part'} = $s3 if ($link);
1548 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1550 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1551 $marcurl->{'MARCURL'} = $url;
1553 push @marcurls, $marcurl;
1559 =head2 GetMarcSeries
1561 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1563 Get all series from the MARC record and returns them in an array.
1564 The series are stored in differents places depending on MARC flavour
1569 my ( $record, $marcflavour ) = @_;
1570 my ( $mintag, $maxtag );
1571 if ( $marcflavour eq "MARC21" ) {
1574 } else { # assume unimarc if not marc21
1584 foreach my $field ( $record->field('440'), $record->field('490') ) {
1587 #my $value = $field->subfield('a');
1588 #$marcsubjct = {MARCSUBJCT => $value,};
1589 my @subfields = $field->subfields();
1591 #warn "subfields:".join " ", @$subfields;
1594 for my $series_subfield (@subfields) {
1596 undef $volume_number;
1598 # see if this is an instance of a volume
1599 if ( $series_subfield->[0] eq 'v' ) {
1603 my $code = $series_subfield->[0];
1604 my $value = $series_subfield->[1];
1605 my $linkvalue = $value;
1606 $linkvalue =~ s/(\(|\))//g;
1607 my $operator = " and " unless $counter == 0;
1608 push @link_loop, { link => $linkvalue, operator => $operator };
1609 my $separator = C4::Context->preference("authoritysep") unless $counter == 0;
1610 if ($volume_number) {
1611 push @subfields_loop, { volumenum => $value };
1613 push @subfields_loop, { code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number } unless ( $series_subfield->[0] eq '9' );
1617 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1619 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1620 #push @marcsubjcts, $marcsubjct;
1624 my $marcseriessarray = \@marcseries;
1625 return $marcseriessarray;
1626 } #end getMARCseriess
1628 =head2 GetFrameworkCode
1630 $frameworkcode = GetFrameworkCode( $biblionumber )
1634 sub GetFrameworkCode {
1635 my ($biblionumber) = @_;
1636 my $dbh = C4::Context->dbh;
1637 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1638 $sth->execute($biblionumber);
1639 my ($frameworkcode) = $sth->fetchrow;
1640 return $frameworkcode;
1643 =head2 TransformKohaToMarc
1645 $record = TransformKohaToMarc( $hash )
1647 This function builds partial MARC::Record from a hash
1648 Hash entries can be from biblio or biblioitems.
1650 This function is called in acquisition module, to create a basic catalogue entry from user entry
1654 sub TransformKohaToMarc {
1656 my $sth = C4::Context->dbh->prepare( "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?" );
1657 my $record = MARC::Record->new();
1658 SetMarcUnicodeFlag( $record, C4::Context->preference("marcflavour") );
1659 foreach ( keys %{$hash} ) {
1660 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1665 =head2 TransformKohaToMarcOneField
1667 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1671 sub TransformKohaToMarcOneField {
1672 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1673 $frameworkcode = '' unless $frameworkcode;
1677 if ( !defined $sth ) {
1678 my $dbh = C4::Context->dbh;
1679 $sth = $dbh->prepare( "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?" );
1681 $sth->execute( $frameworkcode, $kohafieldname );
1682 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1683 my @values = split(/\s?\|\s?/, $value, -1);
1685 foreach my $itemvalue (@values){
1686 my $tag = $record->field($tagfield);
1688 $tag->add_subfields( $tagsubfield => $itemvalue );
1689 $record->delete_field($tag);
1690 $record->insert_fields_ordered($tag);
1693 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $itemvalue );
1700 =head2 TransformHtmlToXml
1702 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator,
1703 $ind_tag, $auth_type )
1705 $auth_type contains :
1709 =item - nothing : rebuild a biblio. In UNIMARC the encoding is in 100$a pos 26/27
1711 =item - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1713 =item - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1719 sub TransformHtmlToXml {
1720 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1721 my $xml = MARC::File::XML::header('UTF-8');
1722 $xml .= "<record>\n";
1723 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1724 MARC::File::XML->default_record_format($auth_type);
1726 # in UNIMARC, field 100 contains the encoding
1727 # check that there is one, otherwise the
1728 # MARC::Record->new_from_xml will fail (and Koha will die)
1729 my $unimarc_and_100_exist = 0;
1730 $unimarc_and_100_exist = 1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1735 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1737 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a" ) {
1739 # if we have a 100 field and it's values are not correct, skip them.
1740 # if we don't have any valid 100 field, we will create a default one at the end
1741 my $enc = substr( @$values[$i], 26, 2 );
1742 if ( $enc eq '01' or $enc eq '50' or $enc eq '03' ) {
1743 $unimarc_and_100_exist = 1;
1748 @$values[$i] =~ s/&/&/g;
1749 @$values[$i] =~ s/</</g;
1750 @$values[$i] =~ s/>/>/g;
1751 @$values[$i] =~ s/"/"/g;
1752 @$values[$i] =~ s/'/'/g;
1754 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1755 # utf8::decode( @$values[$i] );
1757 if ( ( @$tags[$i] ne $prevtag ) ) {
1758 $j++ unless ( @$tags[$i] eq "" );
1759 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
1760 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
1761 my $ind1 = _default_ind_to_space($indicator1);
1763 if ( @$indicator[$j] ) {
1764 $ind2 = _default_ind_to_space($indicator2);
1766 warn "Indicator in @$tags[$i] is empty";
1770 $xml .= "</datafield>\n";
1771 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1772 && ( @$values[$i] ne "" ) ) {
1773 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1774 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1780 if ( @$values[$i] ne "" ) {
1783 if ( @$tags[$i] eq "000" ) {
1784 $xml .= "<leader>@$values[$i]</leader>\n";
1787 # rest of the fixed fields
1788 } elsif ( @$tags[$i] < 10 ) {
1789 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1792 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1793 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1798 } else { # @$tags[$i] eq $prevtag
1799 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
1800 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
1801 my $ind1 = _default_ind_to_space($indicator1);
1803 if ( @$indicator[$j] ) {
1804 $ind2 = _default_ind_to_space($indicator2);
1806 warn "Indicator in @$tags[$i] is empty";
1809 if ( @$values[$i] eq "" ) {
1812 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1815 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1818 $prevtag = @$tags[$i];
1820 $xml .= "</datafield>\n" if @$tags > 0;
1821 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist ) {
1823 # warn "SETTING 100 for $auth_type";
1824 my $string = strftime( "%Y%m%d", localtime(time) );
1826 # set 50 to position 26 is biblios, 13 if authorities
1828 $pos = 13 if $auth_type eq 'UNIMARCAUTH';
1829 $string = sprintf( "%-*s", 35, $string );
1830 substr( $string, $pos, 6, "50" );
1831 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1832 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1833 $xml .= "</datafield>\n";
1835 $xml .= "</record>\n";
1836 $xml .= MARC::File::XML::footer();
1840 =head2 _default_ind_to_space
1842 Passed what should be an indicator returns a space
1843 if its undefined or zero length
1847 sub _default_ind_to_space {
1849 if ( !defined $s || $s eq q{} ) {
1855 =head2 TransformHtmlToMarc
1857 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1858 L<$params> is a ref to an array as below:
1860 'tag_010_indicator1_531951' ,
1861 'tag_010_indicator2_531951' ,
1862 'tag_010_code_a_531951_145735' ,
1863 'tag_010_subfield_a_531951_145735' ,
1864 'tag_200_indicator1_873510' ,
1865 'tag_200_indicator2_873510' ,
1866 'tag_200_code_a_873510_673465' ,
1867 'tag_200_subfield_a_873510_673465' ,
1868 'tag_200_code_b_873510_704318' ,
1869 'tag_200_subfield_b_873510_704318' ,
1870 'tag_200_code_e_873510_280822' ,
1871 'tag_200_subfield_e_873510_280822' ,
1872 'tag_200_code_f_873510_110730' ,
1873 'tag_200_subfield_f_873510_110730' ,
1875 L<$cgi> is the CGI object which containts the value.
1876 L<$record> is the MARC::Record object.
1880 sub TransformHtmlToMarc {
1884 # explicitly turn on the UTF-8 flag for all
1885 # 'tag_' parameters to avoid incorrect character
1886 # conversion later on
1887 my $cgi_params = $cgi->Vars;
1888 foreach my $param_name ( keys %$cgi_params ) {
1889 if ( $param_name =~ /^tag_/ ) {
1890 my $param_value = $cgi_params->{$param_name};
1891 if ( utf8::decode($param_value) ) {
1892 $cgi_params->{$param_name} = $param_value;
1895 # FIXME - need to do something if string is not valid UTF-8
1899 # creating a new record
1900 my $record = MARC::Record->new();
1903 while ( $params->[$i] ) { # browse all CGI params
1904 my $param = $params->[$i];
1907 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1908 if ( $param eq 'biblionumber' ) {
1909 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
1910 if ( $biblionumbertagfield < 10 ) {
1911 $newfield = MARC::Field->new( $biblionumbertagfield, $cgi->param($param), );
1913 $newfield = MARC::Field->new( $biblionumbertagfield, '', '', "$biblionumbertagsubfield" => $cgi->param($param), );
1915 push @fields, $newfield if ($newfield);
1916 } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..."
1919 my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) );
1920 my $ind2 = _default_ind_to_space( substr( $cgi->param( $params->[ $i + 1 ] ), 0, 1 ) );
1924 if ( $tag < 10 ) { # no code for theses fields
1925 # in MARC editor, 000 contains the leader.
1926 if ( $tag eq '000' ) {
1927 # Force a fake leader even if not provided to avoid crashing
1928 # during decoding MARC record containing UTF-8 characters
1930 length( $cgi->param($params->[$j+1]) ) == 24
1931 ? $cgi->param( $params->[ $j + 1 ] )
1935 # between 001 and 009 (included)
1936 } elsif ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) {
1937 $newfield = MARC::Field->new( $tag, $cgi->param( $params->[ $j + 1 ] ), );
1940 # > 009, deal with subfields
1942 while ( defined $params->[$j] && $params->[$j] =~ /_code_/ ) { # browse all it's subfield
1943 my $inner_param = $params->[$j];
1945 if ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) { # only if there is a value (code => value)
1946 $newfield->add_subfields( $cgi->param($inner_param) => $cgi->param( $params->[ $j + 1 ] ) );
1949 if ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) { # creating only if there is a value (code => value)
1950 $newfield = MARC::Field->new( $tag, $ind1, $ind2, $cgi->param($inner_param) => $cgi->param( $params->[ $j + 1 ] ), );
1956 push @fields, $newfield if ($newfield);
1961 $record->append_fields(@fields);
1965 # cache inverted MARC field map
1966 our $inverted_field_map;
1968 =head2 TransformMarcToKoha
1970 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1972 Extract data from a MARC bib record into a hashref representing
1973 Koha biblio, biblioitems, and items fields.
1977 sub TransformMarcToKoha {
1978 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
1981 $limit_table = $limit_table || 0;
1982 $frameworkcode = '' unless defined $frameworkcode;
1984 unless ( defined $inverted_field_map ) {
1985 $inverted_field_map = _get_inverted_marc_field_map();
1989 if ( defined $limit_table && $limit_table eq 'items' ) {
1990 $tables{'items'} = 1;
1992 $tables{'items'} = 1;
1993 $tables{'biblio'} = 1;
1994 $tables{'biblioitems'} = 1;
1997 # traverse through record
1998 MARCFIELD: foreach my $field ( $record->fields() ) {
1999 my $tag = $field->tag();
2000 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2001 if ( $field->is_control_field() ) {
2002 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2003 ENTRY: foreach my $entry ( @{$kohafields} ) {
2004 my ( $subfield, $table, $column ) = @{$entry};
2005 next ENTRY unless exists $tables{$table};
2006 my $key = _disambiguate( $table, $column );
2007 if ( $result->{$key} ) {
2008 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $field->data() eq "" ) ) {
2009 $result->{$key} .= " | " . $field->data();
2012 $result->{$key} = $field->data();
2017 # deal with subfields
2018 MARCSUBFIELD: foreach my $sf ( $field->subfields() ) {
2019 my $code = $sf->[0];
2020 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2021 my $value = $sf->[1];
2022 SFENTRY: foreach my $entry ( @{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} } ) {
2023 my ( $table, $column ) = @{$entry};
2024 next SFENTRY unless exists $tables{$table};
2025 my $key = _disambiguate( $table, $column );
2026 if ( $result->{$key} ) {
2027 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $value eq "" ) ) {
2028 $result->{$key} .= " | " . $value;
2031 $result->{$key} = $value;
2038 # modify copyrightdate to keep only the 1st year found
2039 if ( exists $result->{'copyrightdate'} ) {
2040 my $temp = $result->{'copyrightdate'};
2041 $temp =~ m/c(\d\d\d\d)/;
2042 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2043 $result->{'copyrightdate'} = $1;
2044 } else { # if no cYYYY, get the 1st date.
2045 $temp =~ m/(\d\d\d\d)/;
2046 $result->{'copyrightdate'} = $1;
2050 # modify publicationyear to keep only the 1st year found
2051 if ( exists $result->{'publicationyear'} ) {
2052 my $temp = $result->{'publicationyear'};
2053 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2054 $result->{'publicationyear'} = $1;
2055 } else { # if no cYYYY, get the 1st date.
2056 $temp =~ m/(\d\d\d\d)/;
2057 $result->{'publicationyear'} = $1;
2064 sub _get_inverted_marc_field_map {
2066 my $relations = C4::Context->marcfromkohafield;
2068 foreach my $frameworkcode ( keys %{$relations} ) {
2069 foreach my $kohafield ( keys %{ $relations->{$frameworkcode} } ) {
2070 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2071 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2072 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2073 my ( $table, $column ) = split /[.]/, $kohafield, 2;
2074 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2075 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2081 =head2 _disambiguate
2083 $newkey = _disambiguate($table, $field);
2085 This is a temporary hack to distinguish between the
2086 following sets of columns when using TransformMarcToKoha.
2088 items.cn_source & biblioitems.cn_source
2089 items.cn_sort & biblioitems.cn_sort
2091 Columns that are currently NOT distinguished (FIXME
2092 due to lack of time to fully test) are:
2094 biblio.notes and biblioitems.notes
2099 FIXME - this is necessary because prefixing each column
2100 name with the table name would require changing lots
2101 of code and templates, and exposing more of the DB
2102 structure than is good to the UI templates, particularly
2103 since biblio and bibloitems may well merge in a future
2104 version. In the future, it would also be good to
2105 separate DB access and UI presentation field names
2110 sub CountItemsIssued {
2111 my ($biblionumber) = @_;
2112 my $dbh = C4::Context->dbh;
2113 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2114 $sth->execute($biblionumber);
2115 my $row = $sth->fetchrow_hashref();
2116 return $row->{'issuedCount'};
2120 my ( $table, $column ) = @_;
2121 if ( $column eq "cn_sort" or $column eq "cn_source" ) {
2122 return $table . '.' . $column;
2129 =head2 get_koha_field_from_marc
2131 $result->{_disambiguate($table, $field)} =
2132 get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2134 Internal function to map data from the MARC record to a specific non-MARC field.
2135 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2139 sub get_koha_field_from_marc {
2140 my ( $koha_table, $koha_column, $record, $frameworkcode ) = @_;
2141 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table . '.' . $koha_column, $frameworkcode );
2143 foreach my $field ( $record->field($tagfield) ) {
2144 if ( $field->tag() < 10 ) {
2146 $kohafield .= " | " . $field->data();
2148 $kohafield = $field->data();
2151 if ( $field->subfields ) {
2152 my @subfields = $field->subfields();
2153 foreach my $subfieldcount ( 0 .. $#subfields ) {
2154 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2156 $kohafield .= " | " . $subfields[$subfieldcount][1];
2158 $kohafield = $subfields[$subfieldcount][1];
2168 =head2 TransformMarcToKohaOneField
2170 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2174 sub TransformMarcToKohaOneField {
2176 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2177 # only the 1st will be retrieved...
2178 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2180 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $kohatable . "." . $kohafield, $frameworkcode );
2181 foreach my $field ( $record->field($tagfield) ) {
2182 if ( $field->tag() < 10 ) {
2183 if ( $result->{$kohafield} ) {
2184 $result->{$kohafield} .= " | " . $field->data();
2186 $result->{$kohafield} = $field->data();
2189 if ( $field->subfields ) {
2190 my @subfields = $field->subfields();
2191 foreach my $subfieldcount ( 0 .. $#subfields ) {
2192 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2193 if ( $result->{$kohafield} ) {
2194 $result->{$kohafield} .= " | " . $subfields[$subfieldcount][1];
2196 $result->{$kohafield} = $subfields[$subfieldcount][1];
2206 =head1 OTHER FUNCTIONS
2209 =head2 PrepareItemrecordDisplay
2211 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2213 Returns a hash with all the fields for Display a given item data in a template
2215 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2219 sub PrepareItemrecordDisplay {
2221 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2223 my $dbh = C4::Context->dbh;
2224 $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2225 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2226 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2228 # return nothing if we don't have found an existing framework.
2229 return "" unless $tagslib;
2230 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum ) if ($itemnum);
2232 my $authorised_values_sth = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib" );
2233 foreach my $tag ( sort keys %{$tagslib} ) {
2234 my $previous_tag = '';
2237 # loop through each subfield
2239 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2240 next if ( subfield_is_koha_internal_p($subfield) );
2241 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2243 $subfield_data{tag} = $tag;
2244 $subfield_data{subfield} = $subfield;
2245 $subfield_data{countsubfield} = $cntsubf++;
2246 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2248 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2249 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2250 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2251 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2252 $subfield_data{hidden} = "display:none"
2253 if $tagslib->{$tag}->{$subfield}->{hidden};
2254 my ( $x, $defaultvalue );
2256 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2258 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2259 if ( !defined $defaultvalue ) {
2260 $defaultvalue = q||;
2262 $defaultvalue =~ s/"/"/g;
2264 # search for itemcallnumber if applicable
2265 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2266 && C4::Context->preference('itemcallnumber') ) {
2267 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2268 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2269 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2271 $defaultvalue = $temp->subfield($CNsubfield);
2274 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2276 && $defaultvalues->{'callnumber'} ) {
2277 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2279 $defaultvalue = $defaultvalues->{'callnumber'} if $defaultvalues;
2282 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2284 && $defaultvalues->{'branchcode'} ) {
2285 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2287 $defaultvalue = $defaultvalues->{branchcode} if $defaultvalues;
2290 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2291 my @authorised_values;
2294 # builds list, depending on authorised value...
2296 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2297 if ( ( C4::Context->preference("IndependantBranches") )
2298 && ( C4::Context->userenv->{flags} % 2 != 1 ) ) {
2299 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2300 $sth->execute( C4::Context->userenv->{branch} );
2301 push @authorised_values, ""
2302 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2303 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2304 push @authorised_values, $branchcode;
2305 $authorised_lib{$branchcode} = $branchname;
2308 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2310 push @authorised_values, ""
2311 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2312 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2313 push @authorised_values, $branchcode;
2314 $authorised_lib{$branchcode} = $branchname;
2319 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2320 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2322 push @authorised_values, ""
2323 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2324 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2325 push @authorised_values, $itemtype;
2326 $authorised_lib{$itemtype} = $description;
2329 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2330 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2332 my $class_sources = GetClassSources();
2333 my $default_source = C4::Context->preference("DefaultClassificationSource");
2335 foreach my $class_source (sort keys %$class_sources) {
2336 next unless $class_sources->{$class_source}->{'used'} or
2337 ($class_source eq $default_source);
2338 push @authorised_values, $class_source;
2339 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2342 #---- "true" authorised value
2344 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
2345 push @authorised_values, ""
2346 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2347 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2348 push @authorised_values, $value;
2349 $authorised_lib{$value} = $lib;
2352 $subfield_data{marc_value} = CGI::scrolling_list(
2353 -name => 'field_value',
2354 -values => \@authorised_values,
2355 -default => "$defaultvalue",
2356 -labels => \%authorised_lib,
2362 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2364 push( @loop_data, \%subfield_data );
2368 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2369 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2371 'itemtagfield' => $itemtagfield,
2372 'itemtagsubfield' => $itemtagsubfield,
2373 'itemnumber' => $itemnumber,
2374 'iteminformation' => \@loop_data
2381 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2383 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2384 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2385 # =head2 ModZebrafiles
2387 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2391 # sub ModZebrafiles {
2393 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2397 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2398 # unless ( opendir( DIR, "$zebradir" ) ) {
2399 # warn "$zebradir not found";
2403 # my $filename = $zebradir . $biblionumber;
2406 # open( OUTPUT, ">", $filename . ".xml" );
2407 # print OUTPUT $record;
2414 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2416 $biblionumber is the biblionumber we want to index
2418 $op is specialUpdate or delete, and is used to know what we want to do
2420 $server is the server that we want to update
2422 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2423 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2426 $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.
2431 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2432 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2433 my $dbh = C4::Context->dbh;
2435 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2437 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2438 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2440 if ( C4::Context->preference("NoZebra") ) {
2442 # lock the nozebra table : we will read index lines, update them in Perl process
2443 # and write everything in 1 transaction.
2444 # lock the table to avoid someone else overwriting what we are doing
2445 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2446 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2447 if ( $op eq 'specialUpdate' ) {
2449 # OK, we have to add or update the record
2450 # 1st delete (virtually, in indexes), if record actually exists
2452 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2455 # ... add the record
2456 %result = _AddBiblioNoZebra( $biblionumber, $newRecord, $server, %result );
2459 # it's a deletion, delete the record...
2460 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2461 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2464 # ok, now update the database...
2465 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2466 foreach my $key ( keys %result ) {
2467 foreach my $index ( keys %{ $result{$key} } ) {
2468 $sth->execute( $result{$key}->{$index}, $server, $key, $index );
2471 $dbh->do('UNLOCK TABLES');
2475 # we use zebra, just fill zebraqueue table
2477 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2479 AND biblio_auth_number = ?
2482 my $check_sth = $dbh->prepare_cached($check_sql);
2483 $check_sth->execute( $server, $biblionumber, $op );
2484 my ($count) = $check_sth->fetchrow_array;
2485 $check_sth->finish();
2486 if ( $count == 0 ) {
2487 my $sth = $dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2488 $sth->execute( $biblionumber, $server, $op );
2494 =head2 GetNoZebraIndexes
2496 %indexes = GetNoZebraIndexes;
2498 return the data from NoZebraIndexes syspref.
2502 sub GetNoZebraIndexes {
2503 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2505 INDEX: foreach my $line ( split /['"],[\n\r]*/, $no_zebra_indexes ) {
2506 $line =~ /(.*)=>(.*)/;
2507 my $index = $1; # initial ' or " is removed afterwards
2509 $index =~ s/'|"|\s//g;
2510 $fields =~ s/'|"|\s//g;
2511 $indexes{$index} = $fields;
2516 =head1 INTERNAL FUNCTIONS
2518 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2520 function to delete a biblio in NoZebra indexes
2521 This function does NOT delete anything in database : it reads all the indexes entries
2522 that have to be deleted & delete them in the hash
2524 The SQL part is done either :
2525 - after the Add if we are modifying a biblio (delete + add again)
2526 - immediatly after this sub if we are doing a true deletion.
2528 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2532 sub _DelBiblioNoZebra {
2533 my ( $biblionumber, $record, $server ) = @_;
2536 my $dbh = C4::Context->dbh;
2541 if ( $server eq 'biblioserver' ) {
2542 %index = GetNoZebraIndexes;
2544 # get title of the record (to store the 10 first letters with the index)
2545 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2546 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2549 # for authorities, the "title" is the $a mainentry
2550 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2551 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2552 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2553 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2554 $index{'mainmainentry'} = $authref->{'auth_tag_to_report'} . 'a';
2555 $index{'mainentry'} = $authref->{'auth_tag_to_report'} . '*';
2556 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2561 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2562 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2564 # limit to 10 char, should be enough, and limit the DB size
2565 $title = substr( $title, 0, 10 );
2568 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2569 foreach my $field ( $record->fields() ) {
2571 #parse each subfield
2572 next if $field->tag < 10;
2573 foreach my $subfield ( $field->subfields() ) {
2574 my $tag = $field->tag();
2575 my $subfieldcode = $subfield->[0];
2578 # check each index to see if the subfield is stored somewhere
2579 # otherwise, store it in __RAW__ index
2580 foreach my $key ( keys %index ) {
2582 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2583 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2585 my $line = lc $subfield->[1];
2587 # remove meaningless value in the field...
2588 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2590 # ... and split in words
2591 foreach ( split / /, $line ) {
2592 next unless $_; # skip empty values (multiple spaces)
2593 # if the entry is already here, do nothing, the biblionumber has already be removed
2594 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/ ) ) {
2596 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2597 $sth2->execute( $server, $key, $_ );
2598 my $existing_biblionumbers = $sth2->fetchrow;
2601 if ($existing_biblionumbers) {
2603 # warn " existing for $key $_: $existing_biblionumbers";
2604 $result{$key}->{$_} = $existing_biblionumbers;
2605 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2612 # the subfield is not indexed, store it in __RAW__ index anyway
2614 my $line = lc $subfield->[1];
2615 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2617 # ... and split in words
2618 foreach ( split / /, $line ) {
2619 next unless $_; # skip empty values (multiple spaces)
2620 # if the entry is already here, do nothing, the biblionumber has already be removed
2621 unless ( $result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/ ) {
2623 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2624 $sth2->execute( $server, '__RAW__', $_ );
2625 my $existing_biblionumbers = $sth2->fetchrow;
2628 if ($existing_biblionumbers) {
2629 $result{'__RAW__'}->{$_} = $existing_biblionumbers;
2630 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2640 =head2 _AddBiblioNoZebra
2642 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2644 function to add a biblio in NoZebra indexes
2648 sub _AddBiblioNoZebra {
2649 my ( $biblionumber, $record, $server, %result ) = @_;
2650 my $dbh = C4::Context->dbh;
2655 if ( $server eq 'biblioserver' ) {
2656 %index = GetNoZebraIndexes;
2658 # get title of the record (to store the 10 first letters with the index)
2659 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2660 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2663 # warn "server : $server";
2664 # for authorities, the "title" is the $a mainentry
2665 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2666 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2667 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2668 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2669 $index{'mainmainentry'} = $authref->{auth_tag_to_report} . 'a';
2670 $index{'mainentry'} = $authref->{auth_tag_to_report} . '*';
2671 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2674 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2675 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2677 # limit to 10 char, should be enough, and limit the DB size
2678 $title = substr( $title, 0, 10 );
2681 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2682 foreach my $field ( $record->fields() ) {
2684 #parse each subfield
2685 ###FIXME: impossible to index a 001-009 value with NoZebra
2686 next if $field->tag < 10;
2687 foreach my $subfield ( $field->subfields() ) {
2688 my $tag = $field->tag();
2689 my $subfieldcode = $subfield->[0];
2692 # warn "INDEXING :".$subfield->[1];
2693 # check each index to see if the subfield is stored somewhere
2694 # otherwise, store it in __RAW__ index
2695 foreach my $key ( keys %index ) {
2697 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2698 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2700 my $line = lc $subfield->[1];
2702 # remove meaningless value in the field...
2703 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2705 # ... and split in words
2706 foreach ( split / /, $line ) {
2707 next unless $_; # skip empty values (multiple spaces)
2708 # if the entry is already here, improve weight
2710 # warn "managing $_";
2711 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
2712 my $weight = $1 + 1;
2713 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2714 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2717 # get the value if it exist in the nozebra table, otherwise, create it
2718 $sth2->execute( $server, $key, $_ );
2719 my $existing_biblionumbers = $sth2->fetchrow;
2722 if ($existing_biblionumbers) {
2723 $result{$key}->{"$_"} = $existing_biblionumbers;
2724 my $weight = defined $1 ? $1 + 1 : 1;
2725 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2726 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2728 # create a new ligne for this entry
2731 # warn "INSERT : $server / $key / $_";
2732 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname=' . $dbh->quote($key) . ',value=' . $dbh->quote($_) );
2733 $result{$key}->{"$_"} .= "$biblionumber,$title-1;";
2740 # the subfield is not indexed, store it in __RAW__ index anyway
2742 my $line = lc $subfield->[1];
2743 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2745 # ... and split in words
2746 foreach ( split / /, $line ) {
2747 next unless $_; # skip empty values (multiple spaces)
2748 # if the entry is already here, improve weight
2749 my $tmpstr = $result{'__RAW__'}->{"$_"} || "";
2750 if ( $tmpstr =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
2751 my $weight = $1 + 1;
2752 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2753 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2756 # get the value if it exist in the nozebra table, otherwise, create it
2757 $sth2->execute( $server, '__RAW__', $_ );
2758 my $existing_biblionumbers = $sth2->fetchrow;
2761 if ($existing_biblionumbers) {
2762 $result{'__RAW__'}->{"$_"} = $existing_biblionumbers;
2763 my $weight = ( $1 ? $1 : 0 ) + 1;
2764 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2765 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2767 # create a new ligne for this entry
2769 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname="__RAW__",value=' . $dbh->quote($_) );
2770 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-1;";
2782 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2784 Find the given $subfield in the given $tag in the given
2785 MARC::Record $record. If the subfield is found, returns
2786 the (indicators, value) pair; otherwise, (undef, undef) is
2790 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2791 I suggest we export it from this module.
2796 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2799 if ( $tagfield < 10 ) {
2800 if ( $record->field($tagfield) ) {
2801 push @result, $record->field($tagfield)->data();
2806 foreach my $field ( $record->field($tagfield) ) {
2807 my @subfields = $field->subfields();
2808 foreach my $subfield (@subfields) {
2809 if ( @$subfield[0] eq $insubfield ) {
2810 push @result, @$subfield[1];
2811 $indicator = $field->indicator(1) . $field->indicator(2);
2816 return ( $indicator, @result );
2819 =head2 _koha_marc_update_bib_ids
2822 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2824 Internal function to add or update biblionumber and biblioitemnumber to
2829 sub _koha_marc_update_bib_ids {
2830 my ( $record, $frameworkcode, $biblionumber, $biblioitemnumber ) = @_;
2832 # we must add bibnum and bibitemnum in MARC::Record...
2833 # we build the new field with biblionumber and biblioitemnumber
2834 # we drop the original field
2835 # we add the new builded field.
2836 my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
2837 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
2839 if ( $biblio_tag != $biblioitem_tag ) {
2841 # biblionumber & biblioitemnumber are in different fields
2843 # deal with biblionumber
2844 my ( $new_field, $old_field );
2845 if ( $biblio_tag < 10 ) {
2846 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2848 $new_field = MARC::Field->new( $biblio_tag, '', '', "$biblio_subfield" => $biblionumber );
2851 # drop old field and create new one...
2852 $old_field = $record->field($biblio_tag);
2853 $record->delete_field($old_field) if $old_field;
2854 $record->append_fields($new_field);
2856 # deal with biblioitemnumber
2857 if ( $biblioitem_tag < 10 ) {
2858 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2860 $new_field = MARC::Field->new( $biblioitem_tag, '', '', "$biblioitem_subfield" => $biblioitemnumber, );
2863 # drop old field and create new one...
2864 $old_field = $record->field($biblioitem_tag);
2865 $record->delete_field($old_field) if $old_field;
2866 $record->insert_fields_ordered($new_field);
2870 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2871 my $new_field = MARC::Field->new(
2872 $biblio_tag, '', '',
2873 "$biblio_subfield" => $biblionumber,
2874 "$biblioitem_subfield" => $biblioitemnumber
2877 # drop old field and create new one...
2878 my $old_field = $record->field($biblio_tag);
2879 $record->delete_field($old_field) if $old_field;
2880 $record->insert_fields_ordered($new_field);
2884 =head2 _koha_marc_update_biblioitem_cn_sort
2886 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2888 Given a MARC bib record and the biblioitem hash, update the
2889 subfield that contains a copy of the value of biblioitems.cn_sort.
2893 sub _koha_marc_update_biblioitem_cn_sort {
2895 my $biblioitem = shift;
2896 my $frameworkcode = shift;
2898 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.cn_sort", $frameworkcode );
2899 return unless $biblioitem_tag;
2901 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2903 if ( my $field = $marc->field($biblioitem_tag) ) {
2904 $field->delete_subfield( code => $biblioitem_subfield );
2905 if ( $cn_sort ne '' ) {
2906 $field->add_subfields( $biblioitem_subfield => $cn_sort );
2910 # if we get here, no biblioitem tag is present in the MARC record, so
2911 # we'll create it if $cn_sort is not empty -- this would be
2912 # an odd combination of events, however
2914 $marc->insert_grouped_field( MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) );
2919 =head2 _koha_add_biblio
2921 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2923 Internal function to add a biblio ($biblio is a hash with the values)
2927 sub _koha_add_biblio {
2928 my ( $dbh, $biblio, $frameworkcode ) = @_;
2932 # set the series flag
2933 unless (defined $biblio->{'serial'}){
2934 $biblio->{'serial'} = 0;
2935 if ( $biblio->{'seriestitle'} ) { $biblio->{'serial'} = 1 }
2938 my $query = "INSERT INTO biblio
2939 SET frameworkcode = ?,
2950 my $sth = $dbh->prepare($query);
2952 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
2953 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}
2956 my $biblionumber = $dbh->{'mysql_insertid'};
2957 if ( $dbh->errstr ) {
2958 $error .= "ERROR in _koha_add_biblio $query" . $dbh->errstr;
2964 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
2965 return ( $biblionumber, $error );
2968 =head2 _koha_modify_biblio
2970 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
2972 Internal function for updating the biblio table
2976 sub _koha_modify_biblio {
2977 my ( $dbh, $biblio, $frameworkcode ) = @_;
2982 SET frameworkcode = ?,
2991 WHERE biblionumber = ?
2994 my $sth = $dbh->prepare($query);
2997 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
2998 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}, $biblio->{'biblionumber'}
2999 ) if $biblio->{'biblionumber'};
3001 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3002 $error .= "ERROR in _koha_modify_biblio $query" . $dbh->errstr;
3005 return ( $biblio->{'biblionumber'}, $error );
3008 =head2 _koha_modify_biblioitem_nonmarc
3010 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3012 Updates biblioitems row except for marc and marcxml, which should be changed
3017 sub _koha_modify_biblioitem_nonmarc {
3018 my ( $dbh, $biblioitem ) = @_;
3021 # re-calculate the cn_sort, it may have changed
3022 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3024 my $query = "UPDATE biblioitems
3025 SET biblionumber = ?,
3031 publicationyear = ?,
3035 collectiontitle = ?,
3037 collectionvolume= ?,
3038 editionstatement= ?,
3039 editionresponsibility = ?,
3053 where biblioitemnumber = ?
3055 my $sth = $dbh->prepare($query);
3057 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3058 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3059 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3060 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3061 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3062 $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'},
3063 $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'},
3064 $biblioitem->{'biblioitemnumber'}
3066 if ( $dbh->errstr ) {
3067 $error .= "ERROR in _koha_modify_biblioitem_nonmarc $query" . $dbh->errstr;
3070 return ( $biblioitem->{'biblioitemnumber'}, $error );
3073 =head2 _koha_add_biblioitem
3075 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3077 Internal function to add a biblioitem
3081 sub _koha_add_biblioitem {
3082 my ( $dbh, $biblioitem ) = @_;
3085 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3086 my $query = "INSERT INTO biblioitems SET
3093 publicationyear = ?,
3097 collectiontitle = ?,
3099 collectionvolume= ?,
3100 editionstatement= ?,
3101 editionresponsibility = ?,
3117 my $sth = $dbh->prepare($query);
3119 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3120 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3121 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3122 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3123 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3124 $biblioitem->{'lccn'}, $biblioitem->{'marc'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'},
3125 $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort,
3126 $biblioitem->{'totalissues'}
3128 my $bibitemnum = $dbh->{'mysql_insertid'};
3130 if ( $dbh->errstr ) {
3131 $error .= "ERROR in _koha_add_biblioitem $query" . $dbh->errstr;
3135 return ( $bibitemnum, $error );
3138 =head2 _koha_delete_biblio
3140 $error = _koha_delete_biblio($dbh,$biblionumber);
3142 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3144 C<$dbh> - the database handle
3146 C<$biblionumber> - the biblionumber of the biblio to be deleted
3150 # FIXME: add error handling
3152 sub _koha_delete_biblio {
3153 my ( $dbh, $biblionumber ) = @_;
3155 # get all the data for this biblio
3156 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3157 $sth->execute($biblionumber);
3159 if ( my $data = $sth->fetchrow_hashref ) {
3161 # save the record in deletedbiblio
3162 # find the fields to save
3163 my $query = "INSERT INTO deletedbiblio SET ";
3165 foreach my $temp ( keys %$data ) {
3166 $query .= "$temp = ?,";
3167 push( @bind, $data->{$temp} );
3170 # replace the last , by ",?)"
3172 my $bkup_sth = $dbh->prepare($query);
3173 $bkup_sth->execute(@bind);
3177 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3178 $del_sth->execute($biblionumber);
3185 =head2 _koha_delete_biblioitems
3187 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3189 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3191 C<$dbh> - the database handle
3192 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3196 # FIXME: add error handling
3198 sub _koha_delete_biblioitems {
3199 my ( $dbh, $biblioitemnumber ) = @_;
3201 # get all the data for this biblioitem
3202 my $sth = $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3203 $sth->execute($biblioitemnumber);
3205 if ( my $data = $sth->fetchrow_hashref ) {
3207 # save the record in deletedbiblioitems
3208 # find the fields to save
3209 my $query = "INSERT INTO deletedbiblioitems SET ";
3211 foreach my $temp ( keys %$data ) {
3212 $query .= "$temp = ?,";
3213 push( @bind, $data->{$temp} );
3216 # replace the last , by ",?)"
3218 my $bkup_sth = $dbh->prepare($query);
3219 $bkup_sth->execute(@bind);
3222 # delete the biblioitem
3223 my $del_sth = $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3224 $del_sth->execute($biblioitemnumber);
3231 =head1 UNEXPORTED FUNCTIONS
3233 =head2 ModBiblioMarc
3235 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3237 Add MARC data for a biblio to koha
3239 Function exported, but should NOT be used, unless you really know what you're doing
3245 # pass the MARC::Record to this function, and it will create the records in the marc field
3246 my ( $record, $biblionumber, $frameworkcode ) = @_;
3247 my $dbh = C4::Context->dbh;
3248 my @fields = $record->fields();
3249 if ( !$frameworkcode ) {
3250 $frameworkcode = "";
3252 my $sth = $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3253 $sth->execute( $frameworkcode, $biblionumber );
3255 my $encoding = C4::Context->preference("marcflavour");
3257 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3258 if ( $encoding eq "UNIMARC" ) {
3259 my $string = $record->subfield( 100, "a" );
3260 if ( ($string) && ( length( $record->subfield( 100, "a" ) ) == 36 ) ) {
3261 my $f100 = $record->field(100);
3262 $record->delete_field($f100);
3264 $string = POSIX::strftime( "%Y%m%d", localtime );
3266 $string = sprintf( "%-*s", 35, $string );
3268 substr( $string, 22, 6, "frey50" );
3269 unless ( $record->subfield( 100, "a" ) ) {
3270 $record->insert_grouped_field( MARC::Field->new( 100, "", "", "a" => $string ) );
3274 #enhancement 5374: update transaction date (005) for marc21/unimarc
3275 if($encoding =~ /MARC21|UNIMARC/) {
3276 my @a= (localtime) [5,4,3,2,1,0]; $a[0]+=1900; $a[1]++;
3277 # YY MM DD HH MM SS (update year and month)
3278 my $f005= $record->field('005');
3279 $f005->update(sprintf("%4d%02d%02d%02d%02d%04.1f",@a)) if $f005;
3283 if ( C4::Context->preference("NoZebra") ) {
3285 # only NoZebra indexing needs to have
3286 # the previous version of the record
3287 $oldRecord = GetMarcBiblio($biblionumber);
3289 $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3290 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding), $biblionumber );
3292 ModZebra( $biblionumber, "specialUpdate", "biblioserver", $oldRecord, $record );
3293 return $biblionumber;
3296 =head2 z3950_extended_services
3298 z3950_extended_services($serviceType,$serviceOptions,$record);
3300 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.
3302 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3304 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3306 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3310 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3311 syntax => the record syntax (transfer syntax)
3312 databaseName = Database from connection object
3314 To set serviceOptions, call set_service_options($serviceType)
3316 C<$record> the record, if one is needed for the service type
3318 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3322 sub z3950_extended_services {
3323 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3325 # get our connection object
3326 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3328 # create a new package object
3329 my $Zpackage = $Zconn->package();
3332 $Zpackage->option( action => $action );
3334 if ( $serviceOptions->{'databaseName'} ) {
3335 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3337 if ( $serviceOptions->{'recordIdNumber'} ) {
3338 $Zpackage->option( recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3340 if ( $serviceOptions->{'recordIdOpaque'} ) {
3341 $Zpackage->option( recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3344 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3345 #if ($serviceType eq 'itemorder') {
3346 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3347 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3348 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3349 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3352 if ( $serviceOptions->{record} ) {
3353 $Zpackage->option( record => $serviceOptions->{record} );
3355 # can be xml or marc
3356 if ( $serviceOptions->{'syntax'} ) {
3357 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3361 # send the request, handle any exception encountered
3362 eval { $Zpackage->send($serviceType) };
3363 if ( $@ && $@->isa("ZOOM::Exception") ) {
3364 return "error: " . $@->code() . " " . $@->message() . "\n";
3367 # free up package resources
3368 $Zpackage->destroy();
3371 =head2 set_service_options
3373 my $serviceOptions = set_service_options($serviceType);
3375 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3377 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3381 sub set_service_options {
3382 my ($serviceType) = @_;
3385 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3386 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3388 if ( $serviceType eq 'commit' ) {
3392 if ( $serviceType eq 'create' ) {
3396 if ( $serviceType eq 'drop' ) {
3397 die "ERROR: 'drop' not currently supported (by Zebra)";
3399 return $serviceOptions;
3402 =head2 get_biblio_authorised_values
3404 find the types and values for all authorised values assigned to this biblio.
3408 MARC::Record of the bib
3410 returns: a hashref mapping the authorised value to the value set for this biblionumber
3412 $authorised_values = {
3413 'Scent' => 'flowery',
3414 'Audience' => 'Young Adult',
3415 'itemtypes' => 'SER',
3418 Notes: forlibrarian should probably be passed in, and called something different.
3422 sub get_biblio_authorised_values {
3423 my $biblionumber = shift;
3426 my $forlibrarian = 1; # are we in staff or opac?
3427 my $frameworkcode = GetFrameworkCode($biblionumber);
3429 my $authorised_values;
3431 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3432 or return $authorised_values;
3434 # assume that these entries in the authorised_value table are bibliolevel.
3435 # ones that start with 'item%' are item level.
3436 my $query = q(SELECT distinct authorised_value, kohafield
3437 FROM marc_subfield_structure
3438 WHERE authorised_value !=''
3439 AND (kohafield like 'biblio%'
3440 OR kohafield like '') );
3441 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3443 foreach my $tag ( keys(%$tagslib) ) {
3444 foreach my $subfield ( keys( %{ $tagslib->{$tag} } ) ) {
3446 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3447 if ( 'HASH' eq ref $tagslib->{$tag}{$subfield} ) {
3448 if ( defined $tagslib->{$tag}{$subfield}{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } ) {
3449 if ( defined $record->field($tag) ) {
3450 my $this_subfield_value = $record->field($tag)->subfield($subfield);
3451 if ( defined $this_subfield_value ) {
3452 $authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } = $this_subfield_value;
3460 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3461 return $authorised_values;
3470 Koha Development Team <http://koha-community.org/>
3472 Paul POULAIN paul.poulain@free.fr
3474 Joshua Ferraro jmf@liblime.com