3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2010 BibLibre
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 use MARC::File::USMARC;
29 use POSIX qw(strftime);
32 use C4::Dates qw/format_date/;
33 use C4::Log; # logaction
39 use vars qw($VERSION @ISA @EXPORT);
45 @ISA = qw( Exporter );
60 &GetBiblioItemByBiblioNumber
61 &GetBiblioFromItemNumber
62 &GetBiblionumberFromItemnumber
85 &GetAuthorisedValueDesc
101 # To delete something
106 # To link headings in a bib record
107 # to authority records.
109 &LinkBibHeadingsToAuthorities
113 # those functions are exported but should not be used
114 # they are usefull is few circumstances, so are exported.
115 # but don't use them unless you're a core developer ;-)
123 &TransformHtmlToMarc2
126 &PrepareItemrecordDisplay
132 my $servers = C4::Context->config('memcached_servers');
134 require Memoize::Memcached;
135 import Memoize::Memcached qw(memoize_memcached);
138 servers => [$servers],
139 key_prefix => C4::Context->config('memcached_namespace') || 'koha',
141 memoize_memcached( 'GetMarcStructure', memcached => $memcached, expire_time => 600 ); #cache for 10 minutes
147 C4::Biblio - cataloging management functions
151 Biblio.pm contains functions for managing storage and editing of bibliographic data within Koha. Most of the functions in this module are used for cataloging records: adding, editing, or removing biblios, biblioitems, or items. Koha's stores bibliographic information in three places:
155 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
157 =item 2. as raw MARC in the Zebra index and storage engine
159 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
163 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
165 Because the data isn't completely normalized there's a chance for information to get out of sync. The design choice to go with a un-normalized schema was driven by performance and stability concerns. However, if this occur, it can be considered as a bug : The API is (or should be) complete & the only entry point for all biblio/items managements.
169 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
171 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
175 Because of this design choice, the process of managing storage and editing is a bit convoluted. Historically, Biblio.pm's grown to an unmanagable size and as a result we have several types of functions currently:
179 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
181 =item 2. _koha_* - low-level internal functions for managing the koha tables
183 =item 3. Marc management function : as the MARC record is stored in 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.
185 =item 4. Zebra functions used to update the Zebra index
187 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
191 The MARC record (in 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 :
195 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
197 =item 2. add the biblionumber and biblioitemnumber into the MARC records
199 =item 3. save the marc record
203 When dealing with items, we must :
207 =item 1. save the item in items table, that gives us an itemnumber
209 =item 2. add the itemnumber to the item MARC field
211 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
213 When modifying a biblio or an item, the behaviour is quite similar.
217 =head1 EXPORTED FUNCTIONS
221 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
223 Exported function (core API) for adding a new biblio to koha.
225 The first argument is a C<MARC::Record> object containing the
226 bib to add, while the second argument is the desired MARC
229 This function also accepts a third, optional argument: a hashref
230 to additional options. The only defined option is C<defer_marc_save>,
231 which if present and mapped to a true value, causes C<AddBiblio>
232 to omit the call to save the MARC in C<bibilioitems.marc>
233 and C<biblioitems.marcxml> This option is provided B<only>
234 for the use of scripts such as C<bulkmarcimport.pl> that may need
235 to do some manipulation of the MARC record for item parsing before
236 saving it and which cannot afford the performance hit of saving
237 the MARC record twice. Consequently, do not use that option
238 unless you can guarantee that C<ModBiblioMarc> will be called.
244 my $frameworkcode = shift;
245 my $options = @_ ? shift : undef;
246 my $defer_marc_save = 0;
247 if ( defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'} ) {
248 $defer_marc_save = 1;
251 my ( $biblionumber, $biblioitemnumber, $error );
252 my $dbh = C4::Context->dbh;
254 # transform the data into koha-table style data
255 SetUTF8Flag($record);
256 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
257 ( $biblionumber, $error ) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
258 $olddata->{'biblionumber'} = $biblionumber;
259 ( $biblioitemnumber, $error ) = _koha_add_biblioitem( $dbh, $olddata );
261 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
263 # update MARC subfield that stores biblioitems.cn_sort
264 _koha_marc_update_biblioitem_cn_sort( $record, $olddata, $frameworkcode );
267 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
269 logaction( "CATALOGUING", "ADD", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
270 return ( $biblionumber, $biblioitemnumber );
275 ModBiblio( $record,$biblionumber,$frameworkcode);
277 Replace an existing bib record identified by C<$biblionumber>
278 with one supplied by the MARC::Record object C<$record>. The embedded
279 item, biblioitem, and biblionumber fields from the previous
280 version of the bib record replace any such fields of those tags that
281 are present in C<$record>. Consequently, ModBiblio() is not
282 to be used to try to modify item records.
284 C<$frameworkcode> specifies the MARC framework to use
285 when storing the modified bib record; among other things,
286 this controls how MARC fields get mapped to display columns
287 in the C<biblio> and C<biblioitems> tables, as well as
288 which fields are used to store embedded item, biblioitem,
289 and biblionumber data for indexing.
294 my ( $record, $biblionumber, $frameworkcode ) = @_;
295 if ( C4::Context->preference("CataloguingLog") ) {
296 my $newrecord = GetMarcBiblio($biblionumber);
297 logaction( "CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>" . $newrecord->as_formatted );
300 SetUTF8Flag($record);
301 my $dbh = C4::Context->dbh;
303 $frameworkcode = "" unless $frameworkcode;
305 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
306 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
307 my $oldRecord = GetMarcBiblio($biblionumber);
309 # delete any item fields from incoming record to avoid
310 # duplication or incorrect data - use AddItem() or ModItem()
312 foreach my $field ( $record->field($itemtag) ) {
313 $record->delete_field($field);
316 # parse each item, and, for an unknown reason, re-encode each subfield
317 # if you don't do that, the record will have encoding mixed
318 # and the biblio will be re-encoded.
319 # strange, I (Paul P.) searched more than 1 day to understand what happends
320 # but could only solve the problem this way...
321 my @fields = $oldRecord->field($itemtag);
322 foreach my $fielditem (@fields) {
324 foreach ( $fielditem->subfields() ) {
325 # re-encode the subfield only if it isn't already in utf-8.
326 my ($tag, $value) = @$_;
327 $tag = Encode::encode('utf-8', $tag) unless utf8::is_utf8($tag);
328 $value = Encode::encode('utf-8', $value) unless utf8::is_utf8($value);
331 $field->add_subfields( $tag => $value );
333 $field = MARC::Field->new( "$itemtag", '', '', $tag => $value );
336 $record->append_fields($field);
339 foreach my $field ($record->fields()) {
340 if (! $field->is_control_field()) {
341 if (scalar($field->subfields()) == 0) {
342 $record->delete_fields($field);
347 # update biblionumber and biblioitemnumber in MARC
348 # FIXME - this is assuming a 1 to 1 relationship between
349 # biblios and biblioitems
350 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
351 $sth->execute($biblionumber);
352 my ($biblioitemnumber) = $sth->fetchrow;
354 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
356 # load the koha-table data object
357 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
359 # update MARC subfield that stores biblioitems.cn_sort
360 _koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode );
362 # update the MARC record (that now contains biblio and items) with the new record data
363 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
365 # modify the other koha tables
366 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
367 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
371 =head2 ModBiblioframework
373 ModBiblioframework($biblionumber,$frameworkcode);
375 Exported function to modify a biblio framework
379 sub ModBiblioframework {
380 my ( $biblionumber, $frameworkcode ) = @_;
381 my $dbh = C4::Context->dbh;
382 my $sth = $dbh->prepare( "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?" );
383 $sth->execute( $frameworkcode, $biblionumber );
389 my $error = &DelBiblio($dbh,$biblionumber);
391 Exported function (core API) for deleting a biblio in koha.
392 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
393 Also backs it up to deleted* tables
394 Checks to make sure there are not issues on any of the items
396 C<$error> : undef unless an error occurs
401 my ($biblionumber) = @_;
402 my $dbh = C4::Context->dbh;
403 my $error; # for error handling
405 # First make sure this biblio has no items attached
406 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
407 $sth->execute($biblionumber);
408 if ( my $itemnumber = $sth->fetchrow ) {
410 # Fix this to use a status the template can understand
411 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
414 return $error if $error;
416 # We delete attached subscriptions
417 my $subscriptions = &C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
418 foreach my $subscription (@$subscriptions) {
419 &C4::Serials::DelSubscription( $subscription->{subscriptionid} );
422 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
423 # for at least 2 reasons :
424 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
425 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
426 # 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)
428 if ( C4::Context->preference("NoZebra") ) {
430 # only NoZebra indexing needs to have
431 # the previous version of the record
432 $oldRecord = GetMarcBiblio($biblionumber);
434 ModZebra( $biblionumber, "recordDelete", "biblioserver", $oldRecord, undef );
436 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
437 $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
438 $sth->execute($biblionumber);
439 while ( my $biblioitemnumber = $sth->fetchrow ) {
441 # delete this biblioitem
442 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
443 return $error if $error;
446 # delete biblio from Koha tables and save in deletedbiblio
447 # must do this *after* _koha_delete_biblioitems, otherwise
448 # delete cascade will prevent deletedbiblioitems rows
449 # from being generated by _koha_delete_biblioitems
450 $error = _koha_delete_biblio( $dbh, $biblionumber );
452 logaction( "CATALOGUING", "DELETE", $biblionumber, "" ) if C4::Context->preference("CataloguingLog");
457 =head2 LinkBibHeadingsToAuthorities
459 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
461 Links bib headings to authority records by checking
462 each authority-controlled field in the C<MARC::Record>
463 object C<$marc>, looking for a matching authority record,
464 and setting the linking subfield $9 to the ID of that
467 If no matching authority exists, or if multiple
468 authorities match, no $9 will be added, and any
469 existing one inthe field will be deleted.
471 Returns the number of heading links changed in the
476 sub LinkBibHeadingsToAuthorities {
479 my $num_headings_changed = 0;
480 foreach my $field ( $bib->fields() ) {
481 my $heading = C4::Heading->new_from_bib_field($field);
482 next unless defined $heading;
485 my $current_link = $field->subfield('9');
487 # look for matching authorities
488 my $authorities = $heading->authorities();
490 # want only one exact match
491 if ( $#{$authorities} == 0 ) {
492 my $authority = MARC::Record->new_from_usmarc( $authorities->[0] );
493 my $authid = $authority->field('001')->data();
494 next if defined $current_link and $current_link eq $authid;
496 $field->delete_subfield( code => '9' ) if defined $current_link;
497 $field->add_subfields( '9', $authid );
498 $num_headings_changed++;
500 if ( defined $current_link ) {
501 $field->delete_subfield( code => '9' );
502 $num_headings_changed++;
507 return $num_headings_changed;
510 =head2 GetRecordValue
512 my $values = GetRecordValue($field, $record, $frameworkcode);
514 Get MARC fields from a keyword defined in fieldmapping table.
519 my ( $field, $record, $frameworkcode ) = @_;
520 my $dbh = C4::Context->dbh;
522 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
523 $sth->execute( $frameworkcode, $field );
527 while ( my $row = $sth->fetchrow_hashref ) {
528 foreach my $field ( $record->field( $row->{fieldcode} ) ) {
529 if ( ( $row->{subfieldcode} ne "" && $field->subfield( $row->{subfieldcode} ) ) ) {
530 foreach my $subfield ( $field->subfield( $row->{subfieldcode} ) ) {
531 push @result, { 'subfield' => $subfield };
534 } elsif ( $row->{subfieldcode} eq "" ) {
535 push @result, { 'subfield' => $field->as_string() };
543 =head2 SetFieldMapping
545 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
547 Set a Field to MARC mapping value, if it already exists we don't add a new one.
551 sub SetFieldMapping {
552 my ( $framework, $field, $fieldcode, $subfieldcode ) = @_;
553 my $dbh = C4::Context->dbh;
555 my $sth = $dbh->prepare('SELECT * FROM fieldmapping WHERE fieldcode = ? AND subfieldcode = ? AND frameworkcode = ? AND field = ?');
556 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
557 if ( not $sth->fetchrow_hashref ) {
559 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
561 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
565 =head2 DeleteFieldMapping
567 DeleteFieldMapping($id);
569 Delete a field mapping from an $id.
573 sub DeleteFieldMapping {
575 my $dbh = C4::Context->dbh;
577 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
581 =head2 GetFieldMapping
583 GetFieldMapping($frameworkcode);
585 Get all field mappings for a specified frameworkcode
589 sub GetFieldMapping {
590 my ($framework) = @_;
591 my $dbh = C4::Context->dbh;
593 my $sth = $dbh->prepare('SELECT * FROM fieldmapping where frameworkcode = ?');
594 $sth->execute($framework);
597 while ( my $row = $sth->fetchrow_hashref ) {
605 $data = &GetBiblioData($biblionumber);
607 Returns information about the book with the given biblionumber.
608 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
609 the C<biblio> and C<biblioitems> tables in the
612 In addition, C<$data-E<gt>{subject}> is the list of the book's
613 subjects, separated by C<" , "> (space, comma, space).
614 If there are multiple biblioitems with the given biblionumber, only
615 the first one is considered.
621 my $dbh = C4::Context->dbh;
623 # my $query = C4::Context->preference('item-level_itypes') ?
624 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
626 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
627 # WHERE biblio.biblionumber = ?
628 # AND biblioitems.biblionumber = biblio.biblionumber
631 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
633 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
634 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
635 WHERE biblio.biblionumber = ?
636 AND biblioitems.biblionumber = biblio.biblionumber ";
638 my $sth = $dbh->prepare($query);
639 $sth->execute($bibnum);
641 $data = $sth->fetchrow_hashref;
645 } # sub GetBiblioData
647 =head2 &GetBiblioItemData
649 $itemdata = &GetBiblioItemData($biblioitemnumber);
651 Looks up the biblioitem with the given biblioitemnumber. Returns a
652 reference-to-hash. The keys are the fields from the C<biblio>,
653 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
654 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
659 sub GetBiblioItemData {
660 my ($biblioitemnumber) = @_;
661 my $dbh = C4::Context->dbh;
662 my $query = "SELECT *,biblioitems.notes AS bnotes
663 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
664 unless ( C4::Context->preference('item-level_itypes') ) {
665 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
667 $query .= " WHERE biblioitemnumber = ? ";
668 my $sth = $dbh->prepare($query);
670 $sth->execute($biblioitemnumber);
671 $data = $sth->fetchrow_hashref;
674 } # sub &GetBiblioItemData
676 =head2 GetBiblioItemByBiblioNumber
678 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
682 sub GetBiblioItemByBiblioNumber {
683 my ($biblionumber) = @_;
684 my $dbh = C4::Context->dbh;
685 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
689 $sth->execute($biblionumber);
691 while ( my $data = $sth->fetchrow_hashref ) {
692 push @results, $data;
699 =head2 GetBiblionumberFromItemnumber
704 sub GetBiblionumberFromItemnumber {
705 my ($itemnumber) = @_;
706 my $dbh = C4::Context->dbh;
707 my $sth = $dbh->prepare("Select biblionumber FROM items WHERE itemnumber = ?");
709 $sth->execute($itemnumber);
710 my ($result) = $sth->fetchrow;
714 =head2 GetBiblioFromItemNumber
716 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
718 Looks up the item with the given itemnumber. if undef, try the barcode.
720 C<&itemnodata> returns a reference-to-hash whose keys are the fields
721 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
727 sub GetBiblioFromItemNumber {
728 my ( $itemnumber, $barcode ) = @_;
729 my $dbh = C4::Context->dbh;
732 $sth = $dbh->prepare(
734 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
735 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
736 WHERE items.itemnumber = ?"
738 $sth->execute($itemnumber);
740 $sth = $dbh->prepare(
742 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
743 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
744 WHERE items.barcode = ?"
746 $sth->execute($barcode);
748 my $data = $sth->fetchrow_hashref;
755 $isbd = &GetISBDView($biblionumber);
757 Return the ISBD view which can be included in opac and intranet
762 my ( $biblionumber, $template ) = @_;
763 my $record = GetMarcBiblio($biblionumber);
764 return undef unless defined $record;
765 my $itemtype = &GetFrameworkCode($biblionumber);
766 my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch", $itemtype );
767 my $tagslib = &GetMarcStructure( 1, $itemtype );
769 my $ISBD = C4::Context->preference('isbd');
774 foreach my $isbdfield ( split( /#/, $bloc ) ) {
776 # $isbdfield= /(.?.?.?)/;
777 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
778 my $fieldvalue = $1 || 0;
779 my $subfvalue = $2 || "";
781 my $analysestring = $4;
784 # warn "==> $1 / $2 / $3 / $4";
785 # my $fieldvalue=substr($isbdfield,0,3);
786 if ( $fieldvalue > 0 ) {
787 my $hasputtextbefore = 0;
788 my @fieldslist = $record->field($fieldvalue);
789 @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf );
791 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
792 # warn "FV : $fieldvalue";
793 if ( $subfvalue ne "" ) {
794 foreach my $field (@fieldslist) {
795 foreach my $subfield ( $field->subfield($subfvalue) ) {
796 my $calculated = $analysestring;
797 my $tag = $field->tag();
800 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib );
801 my $tagsubf = $tag . $subfvalue;
802 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
803 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
805 # field builded, store the result
806 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
807 $blocres .= $textbefore;
808 $hasputtextbefore = 1;
811 # remove punctuation at start
812 $calculated =~ s/^( |;|:|\.|-)*//g;
813 $blocres .= $calculated;
818 $blocres .= $textafter if $hasputtextbefore;
820 foreach my $field (@fieldslist) {
821 my $calculated = $analysestring;
822 my $tag = $field->tag();
825 my @subf = $field->subfields;
826 for my $i ( 0 .. $#subf ) {
827 my $valuecode = $subf[$i][1];
828 my $subfieldcode = $subf[$i][0];
829 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib );
830 my $tagsubf = $tag . $subfieldcode;
832 $calculated =~ s/ # replace all {{}} codes by the value code.
833 \{\{$tagsubf\}\} # catch the {{actualcode}}
835 $valuecode # replace by the value code
838 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
839 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
842 # field builded, store the result
843 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
844 $blocres .= $textbefore;
845 $hasputtextbefore = 1;
848 # remove punctuation at start
849 $calculated =~ s/^( |;|:|\.|-)*//g;
850 $blocres .= $calculated;
853 $blocres .= $textafter if $hasputtextbefore;
856 $blocres .= $isbdfield;
861 $res =~ s/\{(.*?)\}//g;
863 $res =~ s/\n/<br\/>/g;
873 ( $count, @results ) = &GetBiblio($biblionumber);
878 my ($biblionumber) = @_;
879 my $dbh = C4::Context->dbh;
880 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
883 $sth->execute($biblionumber);
884 while ( my $data = $sth->fetchrow_hashref ) {
885 $results[$count] = $data;
889 return ( $count, @results );
892 =head2 GetBiblioItemInfosOf
894 GetBiblioItemInfosOf(@biblioitemnumbers);
898 sub GetBiblioItemInfosOf {
899 my @biblioitemnumbers = @_;
902 SELECT biblioitemnumber,
906 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
908 return get_infos_of( $query, 'biblioitemnumber' );
911 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
913 =head2 GetMarcStructure
915 $res = GetMarcStructure($forlibrarian,$frameworkcode);
917 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
918 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
919 $frameworkcode : the framework code to read
923 # cache for results of GetMarcStructure -- needed
925 our $marc_structure_cache;
927 sub GetMarcStructure {
928 my ( $forlibrarian, $frameworkcode ) = @_;
929 my $dbh = C4::Context->dbh;
930 $frameworkcode = "" unless $frameworkcode;
932 if ( defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode} ) {
933 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
936 # my $sth = $dbh->prepare(
937 # "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
938 # $sth->execute($frameworkcode);
939 # my ($total) = $sth->fetchrow;
940 # $frameworkcode = "" unless ( $total > 0 );
941 my $sth = $dbh->prepare(
942 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
943 FROM marc_tag_structure
944 WHERE frameworkcode=?
947 $sth->execute($frameworkcode);
948 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
950 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
951 $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
952 $res->{$tag}->{tab} = "";
953 $res->{$tag}->{mandatory} = $mandatory;
954 $res->{$tag}->{repeatable} = $repeatable;
957 $sth = $dbh->prepare(
958 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
959 FROM marc_subfield_structure
960 WHERE frameworkcode=?
961 ORDER BY tagfield,tagsubfield
965 $sth->execute($frameworkcode);
968 my $authorised_value;
979 ( $tag, $subfield, $liblibrarian, $libopac, $tab, $mandatory, $repeatable, $authorised_value,
980 $authtypecode, $value_builder, $kohafield, $seealso, $hidden, $isurl, $link, $defaultvalue
984 $res->{$tag}->{$subfield}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
985 $res->{$tag}->{$subfield}->{tab} = $tab;
986 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
987 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
988 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
989 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
990 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
991 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
992 $res->{$tag}->{$subfield}->{seealso} = $seealso;
993 $res->{$tag}->{$subfield}->{hidden} = $hidden;
994 $res->{$tag}->{$subfield}->{isurl} = $isurl;
995 $res->{$tag}->{$subfield}->{'link'} = $link;
996 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
999 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
1004 =head2 GetUsedMarcStructure
1006 The same function as GetMarcStructure except it just takes field
1007 in tab 0-9. (used field)
1009 my $results = GetUsedMarcStructure($frameworkcode);
1011 C<$results> is a ref to an array which each case containts a ref
1012 to a hash which each keys is the columns from marc_subfield_structure
1014 C<$frameworkcode> is the framework code.
1018 sub GetUsedMarcStructure($) {
1019 my $frameworkcode = shift || '';
1022 FROM marc_subfield_structure
1024 AND frameworkcode = ?
1025 ORDER BY tagfield, tagsubfield
1027 my $sth = C4::Context->dbh->prepare($query);
1028 $sth->execute($frameworkcode);
1029 return $sth->fetchall_arrayref( {} );
1032 =head2 GetMarcFromKohaField
1034 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1036 Returns the MARC fields & subfields mapped to the koha field
1037 for the given frameworkcode
1041 sub GetMarcFromKohaField {
1042 my ( $kohafield, $frameworkcode ) = @_;
1043 return 0, 0 unless $kohafield and defined $frameworkcode;
1044 my $relations = C4::Context->marcfromkohafield;
1045 return ( $relations->{$frameworkcode}->{$kohafield}->[0], $relations->{$frameworkcode}->{$kohafield}->[1] );
1048 =head2 GetMarcBiblio
1050 my $record = GetMarcBiblio($biblionumber);
1052 Returns MARC::Record representing bib identified by
1053 C<$biblionumber>. If no bib exists, returns undef.
1054 The MARC record contains both biblio & item data.
1059 my $biblionumber = shift;
1060 my $dbh = C4::Context->dbh;
1061 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1062 $sth->execute($biblionumber);
1063 my $row = $sth->fetchrow_hashref;
1064 my $marcxml = StripNonXmlChars( $row->{'marcxml'} );
1065 MARC::File::XML->default_record_format( C4::Context->preference('marcflavour') );
1066 my $record = MARC::Record->new();
1069 $record = eval { MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour') ) };
1070 if ($@) { warn " problem with :$biblionumber : $@ \n$marcxml"; }
1072 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1081 my $marcxml = GetXmlBiblio($biblionumber);
1083 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1084 The XML contains both biblio & item datas
1089 my ($biblionumber) = @_;
1090 my $dbh = C4::Context->dbh;
1091 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1092 $sth->execute($biblionumber);
1093 my ($marcxml) = $sth->fetchrow;
1097 =head2 GetCOinSBiblio
1099 my $coins = GetCOinSBiblio($biblionumber);
1101 Returns the COinS(a span) which can be included in a biblio record
1105 sub GetCOinSBiblio {
1106 my ($biblionumber) = @_;
1107 my $record = GetMarcBiblio($biblionumber);
1109 # get the coin format
1111 # can't get a valid MARC::Record object, bail out at this point
1112 warn "We called GetMarcBiblio with a biblionumber that doesn't exist biblionumber=$biblionumber";
1115 my $pos7 = substr $record->leader(), 7, 1;
1116 my $pos6 = substr $record->leader(), 6, 1;
1119 my ( $aulast, $aufirst ) = ( '', '' );
1128 my $titletype = 'b';
1130 # For the purposes of generating COinS metadata, LDR/06-07 can be
1131 # considered the same for UNIMARC and MARC21
1136 'b' => 'manuscript',
1138 'd' => 'manuscript',
1142 'i' => 'audioRecording',
1143 'j' => 'audioRecording',
1146 'm' => 'computerProgram',
1151 'a' => 'journalArticle',
1155 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
1157 if ( $genre eq 'book' ) {
1158 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1161 ##### We must transform mtx to a valable mtx and document type ####
1162 if ( $genre eq 'book' ) {
1164 } elsif ( $genre eq 'journal' ) {
1167 } elsif ( $genre eq 'journalArticle' ) {
1175 $genre = ( $mtx eq 'dc' ) ? "&rft.type=$genre" : "&rft.genre=$genre";
1177 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
1180 $aulast = $record->subfield( '700', 'a' );
1181 $aufirst = $record->subfield( '700', 'b' );
1182 $oauthors = "&rft.au=$aufirst $aulast";
1185 if ( $record->field('200') ) {
1186 for my $au ( $record->field('200')->subfield('g') ) {
1187 $oauthors .= "&rft.au=$au";
1192 ? "&rft.title=" . $record->subfield( '200', 'a' )
1193 : "&rft.title=" . $record->subfield( '200', 'a' ) . "&rft.btitle=" . $record->subfield( '200', 'a' );
1194 $pubyear = $record->subfield( '210', 'd' );
1195 $publisher = $record->subfield( '210', 'c' );
1196 $isbn = $record->subfield( '010', 'a' );
1197 $issn = $record->subfield( '011', 'a' );
1200 # MARC21 need some improve
1203 if ( $record->field('100') ) {
1204 $oauthors .= "&rft.au=" . $record->subfield( '100', 'a' );
1208 if ( $record->field('700') ) {
1209 for my $au ( $record->field('700')->subfield('a') ) {
1210 $oauthors .= "&rft.au=$au";
1213 $title = "&rft." . $titletype . "title=" . $record->subfield( '245', 'a' );
1214 $subtitle = $record->subfield( '245', 'b' ) || '';
1215 $title .= $subtitle;
1216 if ($titletype eq 'a') {
1217 $pubyear = substr $record->field('008')->data(), 7, 4;
1218 $isbn = $record->subfield( '773', 'z' ) || '';
1219 $issn = $record->subfield( '773', 'x' ) || '';
1220 if ($mtx eq 'journal') {
1221 $title .= "&rft.title=" . (($record->subfield( '773', 't' ) || $record->subfield( '773', 'a')));
1223 $title .= "&rft.btitle=" . (($record->subfield( '773', 't' ) || $record->subfield( '773', 'a')) || '');
1225 foreach my $rel ($record->subfield( '773', 'g' )) {
1232 $pubyear = $record->subfield( '260', 'c' ) || '';
1233 $publisher = $record->subfield( '260', 'b' ) || '';
1234 $isbn = $record->subfield( '020', 'a' ) || '';
1235 $issn = $record->subfield( '022', 'a' ) || '';
1240 "ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3A$mtx$genre$title&rft.isbn=$isbn&rft.issn=$issn&rft.aulast=$aulast&rft.aufirst=$aufirst$oauthors&rft.pub=$publisher&rft.date=$pubyear&rft.pages=$pages";
1241 $coins_value =~ s/(\ |&[^a])/\+/g;
1242 $coins_value =~ s/\"/\"\;/g;
1244 #<!-- 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="
1246 return $coins_value;
1252 return the prices in accordance with the Marc format.
1256 my ( $record, $marcflavour ) = @_;
1260 if ( $marcflavour eq "MARC21" ) {
1261 @listtags = ('345', '020');
1263 } elsif ( $marcflavour eq "UNIMARC" ) {
1264 @listtags = ('345', '010');
1270 for my $field ( $record->field(@listtags) ) {
1271 for my $subfield_value ($field->subfield($subfield)){
1273 return $subfield_value if ($subfield_value);
1276 return 0; # no price found
1279 =head2 GetMarcQuantity
1281 return the quantity of a book. Used in acquisition only, when importing a file an iso2709 from a bookseller
1282 Warning : this is not really in the marc standard. In Unimarc, Electre (the most widely used bookseller) use the 969$a
1286 sub GetMarcQuantity {
1287 my ( $record, $marcflavour ) = @_;
1291 if ( $marcflavour eq "MARC21" ) {
1293 } elsif ( $marcflavour eq "UNIMARC" ) {
1294 @listtags = ('969');
1300 for my $field ( $record->field(@listtags) ) {
1301 for my $subfield_value ($field->subfield($subfield)){
1303 if ($subfield_value) {
1304 # in France, the cents separator is the , but sometimes, ppl use a .
1305 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
1306 $subfield_value =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
1307 return $subfield_value;
1311 return 0; # no price found
1315 =head2 GetAuthorisedValueDesc
1317 my $subfieldvalue =get_authorised_value_desc(
1318 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category, $opac);
1320 Retrieve the complete description for a given authorised value.
1322 Now takes $category and $value pair too.
1324 my $auth_value_desc =GetAuthorisedValueDesc(
1325 '','', 'DVD' ,'','','CCODE');
1327 If the optional $opac parameter is set to a true value, displays OPAC
1328 descriptions rather than normal ones when they exist.
1332 sub GetAuthorisedValueDesc {
1333 my ( $tag, $subfield, $value, $framework, $tagslib, $category, $opac ) = @_;
1334 my $dbh = C4::Context->dbh;
1338 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1341 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1342 return C4::Branch::GetBranchName($value);
1346 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1347 return getitemtypeinfo($value)->{description};
1350 #---- "true" authorized value
1351 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1354 if ( $category ne "" ) {
1355 my $sth = $dbh->prepare( "SELECT lib, lib_opac FROM authorised_values WHERE category = ? AND authorised_value = ?" );
1356 $sth->execute( $category, $value );
1357 my $data = $sth->fetchrow_hashref;
1358 return ( $opac && $data->{'lib_opac'} ) ? $data->{'lib_opac'} : $data->{'lib'};
1360 return $value; # if nothing is found return the original value
1364 =head2 GetMarcControlnumber
1366 $marccontrolnumber = GetMarcControlnumber($record,$marcflavour);
1368 Get the control number / record Identifier from the MARC record and return it.
1372 sub GetMarcControlnumber {
1373 my ( $record, $marcflavour ) = @_;
1374 my $controlnumber = "";
1375 # Control number or Record identifier are the same field in MARC21 and UNIMARC
1376 # Keep $marcflavour for possible later use
1377 if ($marcflavour eq "MARC21" || $marcflavour eq "UNIMARC") {
1378 my $controlnumberField = $record->field('001');
1379 if ($controlnumberField) {
1380 $controlnumber = $controlnumberField->data();
1383 return $controlnumber;
1388 $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
1390 Get all ISBNs from the MARC record and returns them in an array.
1391 ISBNs stored in differents places depending on MARC flavour
1396 my ( $record, $marcflavour ) = @_;
1398 if ( $marcflavour eq "UNIMARC" ) {
1400 } else { # assume marc21 if not unimarc
1407 foreach my $field ( $record->field($scope) ) {
1408 my $value = $field->as_string();
1409 if ( $isbn ne "" ) {
1410 $marcisbn = { marcisbn => $isbn, };
1411 push @marcisbns, $marcisbn;
1414 if ( $isbn ne $value ) {
1415 $isbn = $isbn . " " . $value;
1420 $marcisbn = { marcisbn => $isbn };
1421 push @marcisbns, $marcisbn; #load last tag into array
1428 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1430 Get all notes from the MARC record and returns them in an array.
1431 The note are stored in differents places depending on MARC flavour
1436 my ( $record, $marcflavour ) = @_;
1438 if ( $marcflavour eq "UNIMARC" ) {
1440 } else { # assume marc21 if not unimarc
1447 foreach my $field ( $record->field($scope) ) {
1448 my $value = $field->as_string();
1449 if ( $note ne "" ) {
1450 $marcnote = { marcnote => $note, };
1451 push @marcnotes, $marcnote;
1454 if ( $note ne $value ) {
1455 $note = $note . " " . $value;
1460 $marcnote = { marcnote => $note };
1461 push @marcnotes, $marcnote; #load last tag into array
1464 } # end GetMarcNotes
1466 =head2 GetMarcSubjects
1468 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1470 Get all subjects from the MARC record and returns them in an array.
1471 The subjects are stored in differents places depending on MARC flavour
1475 sub GetMarcSubjects {
1476 my ( $record, $marcflavour ) = @_;
1477 my ( $mintag, $maxtag );
1478 if ( $marcflavour eq "UNIMARC" ) {
1481 } else { # assume marc21 if not unimarc
1491 my $subject_limit = C4::Context->preference("TraceCompleteSubfields") ? 'su,complete-subfield' : 'su';
1493 foreach my $field ( $record->field('6..') ) {
1494 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1496 my @subfields = $field->subfields();
1500 # if there is an authority link, build the link with an= subfield9
1502 for my $subject_subfield (@subfields) {
1504 # don't load unimarc subfields 3,4,5
1505 next if ( ( $marcflavour eq "UNIMARC" ) and ( $subject_subfield->[0] =~ /2|3|4|5/ ) );
1507 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1508 next if ( ( $marcflavour eq "MARC21" ) and ( $subject_subfield->[0] =~ /2/ ) );
1509 my $code = $subject_subfield->[0];
1510 my $value = $subject_subfield->[1];
1511 my $linkvalue = $value;
1512 $linkvalue =~ s/(\(|\))//g;
1513 my $operator = " and " unless $counter == 0;
1516 @link_loop = ( { 'limit' => 'an', link => "$linkvalue" } );
1518 if ( not $found9 ) {
1519 push @link_loop, { 'limit' => $subject_limit, link => $linkvalue, operator => $operator };
1521 my $separator = C4::Context->preference("authoritysep") unless $counter == 0;
1524 my @this_link_loop = @link_loop;
1525 push @subfields_loop, { code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator } unless ( $subject_subfield->[0] eq 9 );
1529 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1532 return \@marcsubjects;
1533 } #end getMARCsubjects
1535 =head2 GetMarcAuthors
1537 authors = GetMarcAuthors($record,$marcflavour);
1539 Get all authors from the MARC record and returns them in an array.
1540 The authors are stored in differents places depending on MARC flavour
1544 sub GetMarcAuthors {
1545 my ( $record, $marcflavour ) = @_;
1546 my ( $mintag, $maxtag );
1548 # tagslib useful for UNIMARC author reponsabilities
1550 &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.
1551 if ( $marcflavour eq "UNIMARC" ) {
1554 } elsif ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) { # assume marc21 or normarc if not unimarc
1562 foreach my $field ( $record->fields ) {
1563 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1566 my @subfields = $field->subfields();
1569 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1570 my $subfield9 = $field->subfield('9');
1571 for my $authors_subfield (@subfields) {
1573 # don't load unimarc subfields 3, 5
1574 next if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /3|5/ ) );
1575 my $subfieldcode = $authors_subfield->[0];
1576 my $value = $authors_subfield->[1];
1577 my $linkvalue = $value;
1578 $linkvalue =~ s/(\(|\))//g;
1579 my $operator = " and " unless $count_auth == 0;
1581 # if we have an authority link, use that as the link, otherwise use standard searching
1583 @link_loop = ( { 'limit' => 'an', link => "$subfield9" } );
1586 # reset $linkvalue if UNIMARC author responsibility
1587 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] eq "4" ) ) {
1588 $linkvalue = "(" . GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) . ")";
1590 push @link_loop, { 'limit' => 'au', link => $linkvalue, operator => $operator };
1592 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib )
1593 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /4/ ) );
1594 my @this_link_loop = @link_loop;
1595 my $separator = C4::Context->preference("authoritysep") unless $count_auth == 0;
1596 push @subfields_loop, { code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator } unless ( $authors_subfield->[0] eq '9' );
1599 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1601 return \@marcauthors;
1606 $marcurls = GetMarcUrls($record,$marcflavour);
1608 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1609 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1614 my ( $record, $marcflavour ) = @_;
1617 for my $field ( $record->field('856') ) {
1619 for my $note ( $field->subfield('z') ) {
1620 push @notes, { note => $note };
1622 my @urls = $field->subfield('u');
1623 foreach my $url (@urls) {
1625 if ( $marcflavour eq 'MARC21' ) {
1626 my $s3 = $field->subfield('3');
1627 my $link = $field->subfield('y');
1628 unless ( $url =~ /^\w+:/ ) {
1629 if ( $field->indicator(1) eq '7' ) {
1630 $url = $field->subfield('2') . "://" . $url;
1631 } elsif ( $field->indicator(1) eq '1' ) {
1632 $url = 'ftp://' . $url;
1635 # properly, this should be if ind1=4,
1636 # however we will assume http protocol since we're building a link.
1637 $url = 'http://' . $url;
1641 # TODO handle ind 2 (relationship)
1646 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1647 $marcurl->{'part'} = $s3 if ($link);
1648 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1650 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1651 $marcurl->{'MARCURL'} = $url;
1653 push @marcurls, $marcurl;
1659 =head2 GetMarcSeries
1661 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1663 Get all series from the MARC record and returns them in an array.
1664 The series are stored in differents places depending on MARC flavour
1669 my ( $record, $marcflavour ) = @_;
1670 my ( $mintag, $maxtag );
1671 if ( $marcflavour eq "UNIMARC" ) {
1674 } else { # assume marc21 if not unimarc
1684 foreach my $field ( $record->field('440'), $record->field('490') ) {
1687 #my $value = $field->subfield('a');
1688 #$marcsubjct = {MARCSUBJCT => $value,};
1689 my @subfields = $field->subfields();
1691 #warn "subfields:".join " ", @$subfields;
1694 for my $series_subfield (@subfields) {
1696 undef $volume_number;
1698 # see if this is an instance of a volume
1699 if ( $series_subfield->[0] eq 'v' ) {
1703 my $code = $series_subfield->[0];
1704 my $value = $series_subfield->[1];
1705 my $linkvalue = $value;
1706 $linkvalue =~ s/(\(|\))//g;
1707 my $operator = " and " unless $counter == 0;
1708 push @link_loop, { link => $linkvalue, operator => $operator };
1709 my $separator = C4::Context->preference("authoritysep") unless $counter == 0;
1710 if ($volume_number) {
1711 push @subfields_loop, { volumenum => $value };
1713 push @subfields_loop, { code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number } unless ( $series_subfield->[0] eq '9' );
1717 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1719 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1720 #push @marcsubjcts, $marcsubjct;
1724 my $marcseriessarray = \@marcseries;
1725 return $marcseriessarray;
1726 } #end getMARCseriess
1728 =head2 GetFrameworkCode
1730 $frameworkcode = GetFrameworkCode( $biblionumber )
1734 sub GetFrameworkCode {
1735 my ($biblionumber) = @_;
1736 my $dbh = C4::Context->dbh;
1737 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1738 $sth->execute($biblionumber);
1739 my ($frameworkcode) = $sth->fetchrow;
1740 return $frameworkcode;
1743 =head2 TransformKohaToMarc
1745 $record = TransformKohaToMarc( $hash )
1747 This function builds partial MARC::Record from a hash
1748 Hash entries can be from biblio or biblioitems.
1750 This function is called in acquisition module, to create a basic catalogue entry from user entry
1754 sub TransformKohaToMarc {
1756 my $sth = C4::Context->dbh->prepare( "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?" );
1757 my $record = MARC::Record->new();
1758 SetMarcUnicodeFlag( $record, C4::Context->preference("marcflavour") );
1759 foreach ( keys %{$hash} ) {
1760 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1765 =head2 TransformKohaToMarcOneField
1767 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1771 sub TransformKohaToMarcOneField {
1772 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1773 $frameworkcode = '' unless $frameworkcode;
1777 if ( !defined $sth ) {
1778 my $dbh = C4::Context->dbh;
1779 $sth = $dbh->prepare( "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?" );
1781 $sth->execute( $frameworkcode, $kohafieldname );
1782 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1783 my @values = split(/\s?\|\s?/, $value, -1);
1785 foreach my $itemvalue (@values){
1786 my $tag = $record->field($tagfield);
1788 $tag->add_subfields( $tagsubfield => $itemvalue );
1789 $record->delete_field($tag);
1790 $record->insert_fields_ordered($tag);
1793 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $itemvalue );
1800 =head2 TransformHtmlToXml
1802 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator,
1803 $ind_tag, $auth_type )
1805 $auth_type contains :
1809 =item - nothing : rebuild a biblio. In UNIMARC the encoding is in 100$a pos 26/27
1811 =item - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1813 =item - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1819 sub TransformHtmlToXml {
1820 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1821 my $xml = MARC::File::XML::header('UTF-8');
1822 $xml .= "<record>\n";
1823 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1824 MARC::File::XML->default_record_format($auth_type);
1826 # in UNIMARC, field 100 contains the encoding
1827 # check that there is one, otherwise the
1828 # MARC::Record->new_from_xml will fail (and Koha will die)
1829 my $unimarc_and_100_exist = 0;
1830 $unimarc_and_100_exist = 1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1835 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1837 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a" ) {
1839 # if we have a 100 field and it's values are not correct, skip them.
1840 # if we don't have any valid 100 field, we will create a default one at the end
1841 my $enc = substr( @$values[$i], 26, 2 );
1842 if ( $enc eq '01' or $enc eq '50' or $enc eq '03' ) {
1843 $unimarc_and_100_exist = 1;
1848 @$values[$i] =~ s/&/&/g;
1849 @$values[$i] =~ s/</</g;
1850 @$values[$i] =~ s/>/>/g;
1851 @$values[$i] =~ s/"/"/g;
1852 @$values[$i] =~ s/'/'/g;
1854 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1855 # utf8::decode( @$values[$i] );
1857 if ( ( @$tags[$i] ne $prevtag ) ) {
1858 $j++ unless ( @$tags[$i] eq "" );
1859 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
1860 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
1861 my $ind1 = _default_ind_to_space($indicator1);
1863 if ( @$indicator[$j] ) {
1864 $ind2 = _default_ind_to_space($indicator2);
1866 warn "Indicator in @$tags[$i] is empty";
1870 $xml .= "</datafield>\n";
1871 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1872 && ( @$values[$i] ne "" ) ) {
1873 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1874 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1880 if ( @$values[$i] ne "" ) {
1883 if ( @$tags[$i] eq "000" ) {
1884 $xml .= "<leader>@$values[$i]</leader>\n";
1887 # rest of the fixed fields
1888 } elsif ( @$tags[$i] < 10 ) {
1889 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1892 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1893 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1898 } else { # @$tags[$i] eq $prevtag
1899 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
1900 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
1901 my $ind1 = _default_ind_to_space($indicator1);
1903 if ( @$indicator[$j] ) {
1904 $ind2 = _default_ind_to_space($indicator2);
1906 warn "Indicator in @$tags[$i] is empty";
1909 if ( @$values[$i] eq "" ) {
1912 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1915 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1918 $prevtag = @$tags[$i];
1920 $xml .= "</datafield>\n" if @$tags > 0;
1921 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist ) {
1923 # warn "SETTING 100 for $auth_type";
1924 my $string = strftime( "%Y%m%d", localtime(time) );
1926 # set 50 to position 26 is biblios, 13 if authorities
1928 $pos = 13 if $auth_type eq 'UNIMARCAUTH';
1929 $string = sprintf( "%-*s", 35, $string );
1930 substr( $string, $pos, 6, "50" );
1931 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1932 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1933 $xml .= "</datafield>\n";
1935 $xml .= "</record>\n";
1936 $xml .= MARC::File::XML::footer();
1940 =head2 _default_ind_to_space
1942 Passed what should be an indicator returns a space
1943 if its undefined or zero length
1947 sub _default_ind_to_space {
1949 if ( !defined $s || $s eq q{} ) {
1955 =head2 TransformHtmlToMarc
1957 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1958 L<$params> is a ref to an array as below:
1960 'tag_010_indicator1_531951' ,
1961 'tag_010_indicator2_531951' ,
1962 'tag_010_code_a_531951_145735' ,
1963 'tag_010_subfield_a_531951_145735' ,
1964 'tag_200_indicator1_873510' ,
1965 'tag_200_indicator2_873510' ,
1966 'tag_200_code_a_873510_673465' ,
1967 'tag_200_subfield_a_873510_673465' ,
1968 'tag_200_code_b_873510_704318' ,
1969 'tag_200_subfield_b_873510_704318' ,
1970 'tag_200_code_e_873510_280822' ,
1971 'tag_200_subfield_e_873510_280822' ,
1972 'tag_200_code_f_873510_110730' ,
1973 'tag_200_subfield_f_873510_110730' ,
1975 L<$cgi> is the CGI object which containts the value.
1976 L<$record> is the MARC::Record object.
1980 sub TransformHtmlToMarc {
1984 # explicitly turn on the UTF-8 flag for all
1985 # 'tag_' parameters to avoid incorrect character
1986 # conversion later on
1987 my $cgi_params = $cgi->Vars;
1988 foreach my $param_name ( keys %$cgi_params ) {
1989 if ( $param_name =~ /^tag_/ ) {
1990 my $param_value = $cgi_params->{$param_name};
1991 if ( utf8::decode($param_value) ) {
1992 $cgi_params->{$param_name} = $param_value;
1995 # FIXME - need to do something if string is not valid UTF-8
1999 # creating a new record
2000 my $record = MARC::Record->new();
2003 while ( $params->[$i] ) { # browse all CGI params
2004 my $param = $params->[$i];
2007 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2008 if ( $param eq 'biblionumber' ) {
2009 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
2010 if ( $biblionumbertagfield < 10 ) {
2011 $newfield = MARC::Field->new( $biblionumbertagfield, $cgi->param($param), );
2013 $newfield = MARC::Field->new( $biblionumbertagfield, '', '', "$biblionumbertagsubfield" => $cgi->param($param), );
2015 push @fields, $newfield if ($newfield);
2016 } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..."
2019 my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) );
2020 my $ind2 = _default_ind_to_space( substr( $cgi->param( $params->[ $i + 1 ] ), 0, 1 ) );
2024 if ( $tag < 10 ) { # no code for theses fields
2025 # in MARC editor, 000 contains the leader.
2026 if ( $tag eq '000' ) {
2027 # Force a fake leader even if not provided to avoid crashing
2028 # during decoding MARC record containing UTF-8 characters
2030 length( $cgi->param($params->[$j+1]) ) == 24
2031 ? $cgi->param( $params->[ $j + 1 ] )
2035 # between 001 and 009 (included)
2036 } elsif ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) {
2037 $newfield = MARC::Field->new( $tag, $cgi->param( $params->[ $j + 1 ] ), );
2040 # > 009, deal with subfields
2042 while ( defined $params->[$j] && $params->[$j] =~ /_code_/ ) { # browse all it's subfield
2043 my $inner_param = $params->[$j];
2045 if ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) { # only if there is a value (code => value)
2046 $newfield->add_subfields( $cgi->param($inner_param) => $cgi->param( $params->[ $j + 1 ] ) );
2049 if ( $cgi->param( $params->[ $j + 1 ] ) ne '' ) { # creating only if there is a value (code => value)
2050 $newfield = MARC::Field->new( $tag, $ind1, $ind2, $cgi->param($inner_param) => $cgi->param( $params->[ $j + 1 ] ), );
2056 push @fields, $newfield if ($newfield);
2061 $record->append_fields(@fields);
2065 # cache inverted MARC field map
2066 our $inverted_field_map;
2068 =head2 TransformMarcToKoha
2070 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2072 Extract data from a MARC bib record into a hashref representing
2073 Koha biblio, biblioitems, and items fields.
2077 sub TransformMarcToKoha {
2078 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
2081 $limit_table = $limit_table || 0;
2082 $frameworkcode = '' unless defined $frameworkcode;
2084 unless ( defined $inverted_field_map ) {
2085 $inverted_field_map = _get_inverted_marc_field_map();
2089 if ( defined $limit_table && $limit_table eq 'items' ) {
2090 $tables{'items'} = 1;
2092 $tables{'items'} = 1;
2093 $tables{'biblio'} = 1;
2094 $tables{'biblioitems'} = 1;
2097 # traverse through record
2098 MARCFIELD: foreach my $field ( $record->fields() ) {
2099 my $tag = $field->tag();
2100 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2101 if ( $field->is_control_field() ) {
2102 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2103 ENTRY: foreach my $entry ( @{$kohafields} ) {
2104 my ( $subfield, $table, $column ) = @{$entry};
2105 next ENTRY unless exists $tables{$table};
2106 my $key = _disambiguate( $table, $column );
2107 if ( $result->{$key} ) {
2108 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $field->data() eq "" ) ) {
2109 $result->{$key} .= " | " . $field->data();
2112 $result->{$key} = $field->data();
2117 # deal with subfields
2118 MARCSUBFIELD: foreach my $sf ( $field->subfields() ) {
2119 my $code = $sf->[0];
2120 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2121 my $value = $sf->[1];
2122 SFENTRY: foreach my $entry ( @{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} } ) {
2123 my ( $table, $column ) = @{$entry};
2124 next SFENTRY unless exists $tables{$table};
2125 my $key = _disambiguate( $table, $column );
2126 if ( $result->{$key} ) {
2127 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $value eq "" ) ) {
2128 $result->{$key} .= " | " . $value;
2131 $result->{$key} = $value;
2138 # modify copyrightdate to keep only the 1st year found
2139 if ( exists $result->{'copyrightdate'} ) {
2140 my $temp = $result->{'copyrightdate'};
2141 $temp =~ m/c(\d\d\d\d)/;
2142 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2143 $result->{'copyrightdate'} = $1;
2144 } else { # if no cYYYY, get the 1st date.
2145 $temp =~ m/(\d\d\d\d)/;
2146 $result->{'copyrightdate'} = $1;
2150 # modify publicationyear to keep only the 1st year found
2151 if ( exists $result->{'publicationyear'} ) {
2152 my $temp = $result->{'publicationyear'};
2153 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2154 $result->{'publicationyear'} = $1;
2155 } else { # if no cYYYY, get the 1st date.
2156 $temp =~ m/(\d\d\d\d)/;
2157 $result->{'publicationyear'} = $1;
2164 sub _get_inverted_marc_field_map {
2166 my $relations = C4::Context->marcfromkohafield;
2168 foreach my $frameworkcode ( keys %{$relations} ) {
2169 foreach my $kohafield ( keys %{ $relations->{$frameworkcode} } ) {
2170 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2171 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2172 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2173 my ( $table, $column ) = split /[.]/, $kohafield, 2;
2174 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2175 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2181 =head2 _disambiguate
2183 $newkey = _disambiguate($table, $field);
2185 This is a temporary hack to distinguish between the
2186 following sets of columns when using TransformMarcToKoha.
2188 items.cn_source & biblioitems.cn_source
2189 items.cn_sort & biblioitems.cn_sort
2191 Columns that are currently NOT distinguished (FIXME
2192 due to lack of time to fully test) are:
2194 biblio.notes and biblioitems.notes
2199 FIXME - this is necessary because prefixing each column
2200 name with the table name would require changing lots
2201 of code and templates, and exposing more of the DB
2202 structure than is good to the UI templates, particularly
2203 since biblio and bibloitems may well merge in a future
2204 version. In the future, it would also be good to
2205 separate DB access and UI presentation field names
2210 sub CountItemsIssued {
2211 my ($biblionumber) = @_;
2212 my $dbh = C4::Context->dbh;
2213 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2214 $sth->execute($biblionumber);
2215 my $row = $sth->fetchrow_hashref();
2216 return $row->{'issuedCount'};
2220 my ( $table, $column ) = @_;
2221 if ( $column eq "cn_sort" or $column eq "cn_source" ) {
2222 return $table . '.' . $column;
2229 =head2 get_koha_field_from_marc
2231 $result->{_disambiguate($table, $field)} =
2232 get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2234 Internal function to map data from the MARC record to a specific non-MARC field.
2235 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2239 sub get_koha_field_from_marc {
2240 my ( $koha_table, $koha_column, $record, $frameworkcode ) = @_;
2241 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table . '.' . $koha_column, $frameworkcode );
2243 foreach my $field ( $record->field($tagfield) ) {
2244 if ( $field->tag() < 10 ) {
2246 $kohafield .= " | " . $field->data();
2248 $kohafield = $field->data();
2251 if ( $field->subfields ) {
2252 my @subfields = $field->subfields();
2253 foreach my $subfieldcount ( 0 .. $#subfields ) {
2254 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2256 $kohafield .= " | " . $subfields[$subfieldcount][1];
2258 $kohafield = $subfields[$subfieldcount][1];
2268 =head2 TransformMarcToKohaOneField
2270 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2274 sub TransformMarcToKohaOneField {
2276 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2277 # only the 1st will be retrieved...
2278 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2280 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $kohatable . "." . $kohafield, $frameworkcode );
2281 foreach my $field ( $record->field($tagfield) ) {
2282 if ( $field->tag() < 10 ) {
2283 if ( $result->{$kohafield} ) {
2284 $result->{$kohafield} .= " | " . $field->data();
2286 $result->{$kohafield} = $field->data();
2289 if ( $field->subfields ) {
2290 my @subfields = $field->subfields();
2291 foreach my $subfieldcount ( 0 .. $#subfields ) {
2292 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2293 if ( $result->{$kohafield} ) {
2294 $result->{$kohafield} .= " | " . $subfields[$subfieldcount][1];
2296 $result->{$kohafield} = $subfields[$subfieldcount][1];
2306 =head1 OTHER FUNCTIONS
2309 =head2 PrepareItemrecordDisplay
2311 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2313 Returns a hash with all the fields for Display a given item data in a template
2315 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2319 sub PrepareItemrecordDisplay {
2321 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2323 my $dbh = C4::Context->dbh;
2324 $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2325 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2326 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2328 # return nothing if we don't have found an existing framework.
2329 return "" unless $tagslib;
2330 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum ) if ($itemnum);
2332 my $authorised_values_sth = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib" );
2333 foreach my $tag ( sort keys %{$tagslib} ) {
2334 my $previous_tag = '';
2337 # loop through each subfield
2339 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2340 next if ( subfield_is_koha_internal_p($subfield) );
2341 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2343 $subfield_data{tag} = $tag;
2344 $subfield_data{subfield} = $subfield;
2345 $subfield_data{countsubfield} = $cntsubf++;
2346 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2348 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2349 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2350 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2351 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2352 $subfield_data{hidden} = "display:none"
2353 if $tagslib->{$tag}->{$subfield}->{hidden};
2354 my ( $x, $defaultvalue );
2356 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2358 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2359 if ( !defined $defaultvalue ) {
2360 $defaultvalue = q||;
2362 $defaultvalue =~ s/"/"/g;
2364 # search for itemcallnumber if applicable
2365 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2366 && C4::Context->preference('itemcallnumber') ) {
2367 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2368 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2369 my $temp = $itemrecord->field($CNtag) if ($itemrecord);
2371 $defaultvalue = $temp->subfield($CNsubfield);
2374 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2376 && $defaultvalues->{'callnumber'} ) {
2377 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2379 $defaultvalue = $defaultvalues->{'callnumber'} if $defaultvalues;
2382 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2384 && $defaultvalues->{'branchcode'} ) {
2385 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2387 $defaultvalue = $defaultvalues->{branchcode} if $defaultvalues;
2390 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2392 && $defaultvalues->{'location'} ) {
2393 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2395 $defaultvalue = $defaultvalues->{location} if $defaultvalues;
2398 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2399 my @authorised_values;
2402 # builds list, depending on authorised value...
2404 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2405 if ( ( C4::Context->preference("IndependantBranches") )
2406 && ( C4::Context->userenv->{flags} % 2 != 1 ) ) {
2407 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2408 $sth->execute( C4::Context->userenv->{branch} );
2409 push @authorised_values, ""
2410 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2411 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2412 push @authorised_values, $branchcode;
2413 $authorised_lib{$branchcode} = $branchname;
2416 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2418 push @authorised_values, ""
2419 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2420 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2421 push @authorised_values, $branchcode;
2422 $authorised_lib{$branchcode} = $branchname;
2427 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2428 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2430 push @authorised_values, ""
2431 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2432 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2433 push @authorised_values, $itemtype;
2434 $authorised_lib{$itemtype} = $description;
2437 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2438 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2440 my $class_sources = GetClassSources();
2441 my $default_source = C4::Context->preference("DefaultClassificationSource");
2443 foreach my $class_source (sort keys %$class_sources) {
2444 next unless $class_sources->{$class_source}->{'used'} or
2445 ($class_source eq $default_source);
2446 push @authorised_values, $class_source;
2447 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2450 #---- "true" authorised value
2452 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
2453 push @authorised_values, ""
2454 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2455 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2456 push @authorised_values, $value;
2457 $authorised_lib{$value} = $lib;
2460 $subfield_data{marc_value} = CGI::scrolling_list(
2461 -name => 'field_value',
2462 -values => \@authorised_values,
2463 -default => "$defaultvalue",
2464 -labels => \%authorised_lib,
2469 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2471 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
2474 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2475 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2476 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
2477 my $index_subfield = int(rand(1000000));
2478 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
2479 $subfield_data{marc_value} = qq[<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255"
2480 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
2481 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
2482 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
2485 warn "Plugin Failed: $plugin";
2486 $subfield_data{marc_value} = qq(<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" />); # supply default input form
2489 elsif ( $tag eq '' ) { # it's an hidden field
2490 $subfield_data{marc_value} = qq(<input type="hidden" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" value="$defaultvalue" />);
2492 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2493 $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" value="$defaultvalue" />);
2495 elsif ( length($defaultvalue) > 100
2496 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2497 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2498 or (C4::Context->preference("marcflavour") eq "MARC21" and
2499 500 <= $tag && $tag < 600 )
2501 # oversize field (textarea)
2502 $subfield_data{marc_value} = qq(<textarea tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255">$defaultvalue</textarea>\n");
2504 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2506 push( @loop_data, \%subfield_data );
2510 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2511 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2513 'itemtagfield' => $itemtagfield,
2514 'itemtagsubfield' => $itemtagsubfield,
2515 'itemnumber' => $itemnumber,
2516 'iteminformation' => \@loop_data
2523 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2525 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2526 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2527 # =head2 ModZebrafiles
2529 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2533 # sub ModZebrafiles {
2535 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2539 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2540 # unless ( opendir( DIR, "$zebradir" ) ) {
2541 # warn "$zebradir not found";
2545 # my $filename = $zebradir . $biblionumber;
2548 # open( OUTPUT, ">", $filename . ".xml" );
2549 # print OUTPUT $record;
2556 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2558 $biblionumber is the biblionumber we want to index
2560 $op is specialUpdate or delete, and is used to know what we want to do
2562 $server is the server that we want to update
2564 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2565 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2568 $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.
2573 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2574 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2575 my $dbh = C4::Context->dbh;
2577 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2579 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2580 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2582 if ( C4::Context->preference("NoZebra") ) {
2584 # lock the nozebra table : we will read index lines, update them in Perl process
2585 # and write everything in 1 transaction.
2586 # lock the table to avoid someone else overwriting what we are doing
2587 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2588 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2589 if ( $op eq 'specialUpdate' ) {
2591 # OK, we have to add or update the record
2592 # 1st delete (virtually, in indexes), if record actually exists
2594 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2597 # ... add the record
2598 %result = _AddBiblioNoZebra( $biblionumber, $newRecord, $server, %result );
2601 # it's a deletion, delete the record...
2602 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2603 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2606 # ok, now update the database...
2607 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2608 foreach my $key ( keys %result ) {
2609 foreach my $index ( keys %{ $result{$key} } ) {
2610 $sth->execute( $result{$key}->{$index}, $server, $key, $index );
2613 $dbh->do('UNLOCK TABLES');
2617 # we use zebra, just fill zebraqueue table
2619 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2621 AND biblio_auth_number = ?
2624 my $check_sth = $dbh->prepare_cached($check_sql);
2625 $check_sth->execute( $server, $biblionumber, $op );
2626 my ($count) = $check_sth->fetchrow_array;
2627 $check_sth->finish();
2628 if ( $count == 0 ) {
2629 my $sth = $dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2630 $sth->execute( $biblionumber, $server, $op );
2636 =head2 GetNoZebraIndexes
2638 %indexes = GetNoZebraIndexes;
2640 return the data from NoZebraIndexes syspref.
2644 sub GetNoZebraIndexes {
2645 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2647 INDEX: foreach my $line ( split /['"],[\n\r]*/, $no_zebra_indexes ) {
2648 $line =~ /(.*)=>(.*)/;
2649 my $index = $1; # initial ' or " is removed afterwards
2651 $index =~ s/'|"|\s//g;
2652 $fields =~ s/'|"|\s//g;
2653 $indexes{$index} = $fields;
2658 =head1 INTERNAL FUNCTIONS
2660 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2662 function to delete a biblio in NoZebra indexes
2663 This function does NOT delete anything in database : it reads all the indexes entries
2664 that have to be deleted & delete them in the hash
2666 The SQL part is done either :
2667 - after the Add if we are modifying a biblio (delete + add again)
2668 - immediatly after this sub if we are doing a true deletion.
2670 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2674 sub _DelBiblioNoZebra {
2675 my ( $biblionumber, $record, $server ) = @_;
2678 my $dbh = C4::Context->dbh;
2683 if ( $server eq 'biblioserver' ) {
2684 %index = GetNoZebraIndexes;
2686 # get title of the record (to store the 10 first letters with the index)
2687 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2688 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2691 # for authorities, the "title" is the $a mainentry
2692 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2693 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2694 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2695 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2696 $index{'mainmainentry'} = $authref->{'auth_tag_to_report'} . 'a';
2697 $index{'mainentry'} = $authref->{'auth_tag_to_report'} . '*';
2698 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2703 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2704 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2706 # limit to 10 char, should be enough, and limit the DB size
2707 $title = substr( $title, 0, 10 );
2710 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2711 foreach my $field ( $record->fields() ) {
2713 #parse each subfield
2714 next if $field->tag < 10;
2715 foreach my $subfield ( $field->subfields() ) {
2716 my $tag = $field->tag();
2717 my $subfieldcode = $subfield->[0];
2720 # check each index to see if the subfield is stored somewhere
2721 # otherwise, store it in __RAW__ index
2722 foreach my $key ( keys %index ) {
2724 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2725 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2727 my $line = lc $subfield->[1];
2729 # remove meaningless value in the field...
2730 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2732 # ... and split in words
2733 foreach ( split / /, $line ) {
2734 next unless $_; # skip empty values (multiple spaces)
2735 # if the entry is already here, do nothing, the biblionumber has already be removed
2736 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/ ) ) {
2738 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2739 $sth2->execute( $server, $key, $_ );
2740 my $existing_biblionumbers = $sth2->fetchrow;
2743 if ($existing_biblionumbers) {
2745 # warn " existing for $key $_: $existing_biblionumbers";
2746 $result{$key}->{$_} = $existing_biblionumbers;
2747 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2754 # the subfield is not indexed, store it in __RAW__ index anyway
2756 my $line = lc $subfield->[1];
2757 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2759 # ... and split in words
2760 foreach ( split / /, $line ) {
2761 next unless $_; # skip empty values (multiple spaces)
2762 # if the entry is already here, do nothing, the biblionumber has already be removed
2763 unless ( $result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/ ) {
2765 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2766 $sth2->execute( $server, '__RAW__', $_ );
2767 my $existing_biblionumbers = $sth2->fetchrow;
2770 if ($existing_biblionumbers) {
2771 $result{'__RAW__'}->{$_} = $existing_biblionumbers;
2772 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2782 =head2 _AddBiblioNoZebra
2784 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2786 function to add a biblio in NoZebra indexes
2790 sub _AddBiblioNoZebra {
2791 my ( $biblionumber, $record, $server, %result ) = @_;
2792 my $dbh = C4::Context->dbh;
2797 if ( $server eq 'biblioserver' ) {
2798 %index = GetNoZebraIndexes;
2800 # get title of the record (to store the 10 first letters with the index)
2801 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2802 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2805 # warn "server : $server";
2806 # for authorities, the "title" is the $a mainentry
2807 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2808 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2809 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2810 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2811 $index{'mainmainentry'} = $authref->{auth_tag_to_report} . 'a';
2812 $index{'mainentry'} = $authref->{auth_tag_to_report} . '*';
2813 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2816 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2817 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2819 # limit to 10 char, should be enough, and limit the DB size
2820 $title = substr( $title, 0, 10 );
2823 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2824 foreach my $field ( $record->fields() ) {
2826 #parse each subfield
2827 ###FIXME: impossible to index a 001-009 value with NoZebra
2828 next if $field->tag < 10;
2829 foreach my $subfield ( $field->subfields() ) {
2830 my $tag = $field->tag();
2831 my $subfieldcode = $subfield->[0];
2834 # warn "INDEXING :".$subfield->[1];
2835 # check each index to see if the subfield is stored somewhere
2836 # otherwise, store it in __RAW__ index
2837 foreach my $key ( keys %index ) {
2839 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2840 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2842 my $line = lc $subfield->[1];
2844 # remove meaningless value in the field...
2845 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2847 # ... and split in words
2848 foreach ( split / /, $line ) {
2849 next unless $_; # skip empty values (multiple spaces)
2850 # if the entry is already here, improve weight
2852 # warn "managing $_";
2853 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
2854 my $weight = $1 + 1;
2855 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2856 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2859 # get the value if it exist in the nozebra table, otherwise, create it
2860 $sth2->execute( $server, $key, $_ );
2861 my $existing_biblionumbers = $sth2->fetchrow;
2864 if ($existing_biblionumbers) {
2865 $result{$key}->{"$_"} = $existing_biblionumbers;
2866 my $weight = defined $1 ? $1 + 1 : 1;
2867 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2868 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2870 # create a new ligne for this entry
2873 # warn "INSERT : $server / $key / $_";
2874 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname=' . $dbh->quote($key) . ',value=' . $dbh->quote($_) );
2875 $result{$key}->{"$_"} .= "$biblionumber,$title-1;";
2882 # the subfield is not indexed, store it in __RAW__ index anyway
2884 my $line = lc $subfield->[1];
2885 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2887 # ... and split in words
2888 foreach ( split / /, $line ) {
2889 next unless $_; # skip empty values (multiple spaces)
2890 # if the entry is already here, improve weight
2891 my $tmpstr = $result{'__RAW__'}->{"$_"} || "";
2892 if ( $tmpstr =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
2893 my $weight = $1 + 1;
2894 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2895 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2898 # get the value if it exist in the nozebra table, otherwise, create it
2899 $sth2->execute( $server, '__RAW__', $_ );
2900 my $existing_biblionumbers = $sth2->fetchrow;
2903 if ($existing_biblionumbers) {
2904 $result{'__RAW__'}->{"$_"} = $existing_biblionumbers;
2905 my $weight = ( $1 ? $1 : 0 ) + 1;
2906 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2907 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2909 # create a new ligne for this entry
2911 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname="__RAW__",value=' . $dbh->quote($_) );
2912 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-1;";
2924 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2926 Find the given $subfield in the given $tag in the given
2927 MARC::Record $record. If the subfield is found, returns
2928 the (indicators, value) pair; otherwise, (undef, undef) is
2932 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2933 I suggest we export it from this module.
2938 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2941 if ( $tagfield < 10 ) {
2942 if ( $record->field($tagfield) ) {
2943 push @result, $record->field($tagfield)->data();
2948 foreach my $field ( $record->field($tagfield) ) {
2949 my @subfields = $field->subfields();
2950 foreach my $subfield (@subfields) {
2951 if ( @$subfield[0] eq $insubfield ) {
2952 push @result, @$subfield[1];
2953 $indicator = $field->indicator(1) . $field->indicator(2);
2958 return ( $indicator, @result );
2961 =head2 _koha_marc_update_bib_ids
2964 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2966 Internal function to add or update biblionumber and biblioitemnumber to
2971 sub _koha_marc_update_bib_ids {
2972 my ( $record, $frameworkcode, $biblionumber, $biblioitemnumber ) = @_;
2974 # we must add bibnum and bibitemnum in MARC::Record...
2975 # we build the new field with biblionumber and biblioitemnumber
2976 # we drop the original field
2977 # we add the new builded field.
2978 my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
2979 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
2981 if ( $biblio_tag != $biblioitem_tag ) {
2983 # biblionumber & biblioitemnumber are in different fields
2985 # deal with biblionumber
2986 my ( $new_field, $old_field );
2987 if ( $biblio_tag < 10 ) {
2988 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2990 $new_field = MARC::Field->new( $biblio_tag, '', '', "$biblio_subfield" => $biblionumber );
2993 # drop old field and create new one...
2994 $old_field = $record->field($biblio_tag);
2995 $record->delete_field($old_field) if $old_field;
2996 $record->append_fields($new_field);
2998 # deal with biblioitemnumber
2999 if ( $biblioitem_tag < 10 ) {
3000 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
3002 $new_field = MARC::Field->new( $biblioitem_tag, '', '', "$biblioitem_subfield" => $biblioitemnumber, );
3005 # drop old field and create new one...
3006 $old_field = $record->field($biblioitem_tag);
3007 $record->delete_field($old_field) if $old_field;
3008 $record->insert_fields_ordered($new_field);
3012 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
3013 my $new_field = MARC::Field->new(
3014 $biblio_tag, '', '',
3015 "$biblio_subfield" => $biblionumber,
3016 "$biblioitem_subfield" => $biblioitemnumber
3019 # drop old field and create new one...
3020 my $old_field = $record->field($biblio_tag);
3021 $record->delete_field($old_field) if $old_field;
3022 $record->insert_fields_ordered($new_field);
3026 =head2 _koha_marc_update_biblioitem_cn_sort
3028 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
3030 Given a MARC bib record and the biblioitem hash, update the
3031 subfield that contains a copy of the value of biblioitems.cn_sort.
3035 sub _koha_marc_update_biblioitem_cn_sort {
3037 my $biblioitem = shift;
3038 my $frameworkcode = shift;
3040 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.cn_sort", $frameworkcode );
3041 return unless $biblioitem_tag;
3043 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3045 if ( my $field = $marc->field($biblioitem_tag) ) {
3046 $field->delete_subfield( code => $biblioitem_subfield );
3047 if ( $cn_sort ne '' ) {
3048 $field->add_subfields( $biblioitem_subfield => $cn_sort );
3052 # if we get here, no biblioitem tag is present in the MARC record, so
3053 # we'll create it if $cn_sort is not empty -- this would be
3054 # an odd combination of events, however
3056 $marc->insert_grouped_field( MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) );
3061 =head2 _koha_add_biblio
3063 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3065 Internal function to add a biblio ($biblio is a hash with the values)
3069 sub _koha_add_biblio {
3070 my ( $dbh, $biblio, $frameworkcode ) = @_;
3074 # set the series flag
3075 unless (defined $biblio->{'serial'}){
3076 $biblio->{'serial'} = 0;
3077 if ( $biblio->{'seriestitle'} ) { $biblio->{'serial'} = 1 }
3080 my $query = "INSERT INTO biblio
3081 SET frameworkcode = ?,
3092 my $sth = $dbh->prepare($query);
3094 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
3095 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}
3098 my $biblionumber = $dbh->{'mysql_insertid'};
3099 if ( $dbh->errstr ) {
3100 $error .= "ERROR in _koha_add_biblio $query" . $dbh->errstr;
3106 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3107 return ( $biblionumber, $error );
3110 =head2 _koha_modify_biblio
3112 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3114 Internal function for updating the biblio table
3118 sub _koha_modify_biblio {
3119 my ( $dbh, $biblio, $frameworkcode ) = @_;
3124 SET frameworkcode = ?,
3133 WHERE biblionumber = ?
3136 my $sth = $dbh->prepare($query);
3139 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
3140 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}, $biblio->{'biblionumber'}
3141 ) if $biblio->{'biblionumber'};
3143 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3144 $error .= "ERROR in _koha_modify_biblio $query" . $dbh->errstr;
3147 return ( $biblio->{'biblionumber'}, $error );
3150 =head2 _koha_modify_biblioitem_nonmarc
3152 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3154 Updates biblioitems row except for marc and marcxml, which should be changed
3159 sub _koha_modify_biblioitem_nonmarc {
3160 my ( $dbh, $biblioitem ) = @_;
3163 # re-calculate the cn_sort, it may have changed
3164 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3166 my $query = "UPDATE biblioitems
3167 SET biblionumber = ?,
3173 publicationyear = ?,
3177 collectiontitle = ?,
3179 collectionvolume= ?,
3180 editionstatement= ?,
3181 editionresponsibility = ?,
3195 where biblioitemnumber = ?
3197 my $sth = $dbh->prepare($query);
3199 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3200 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3201 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3202 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3203 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3204 $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'},
3205 $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'},
3206 $biblioitem->{'biblioitemnumber'}
3208 if ( $dbh->errstr ) {
3209 $error .= "ERROR in _koha_modify_biblioitem_nonmarc $query" . $dbh->errstr;
3212 return ( $biblioitem->{'biblioitemnumber'}, $error );
3215 =head2 _koha_add_biblioitem
3217 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3219 Internal function to add a biblioitem
3223 sub _koha_add_biblioitem {
3224 my ( $dbh, $biblioitem ) = @_;
3227 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3228 my $query = "INSERT INTO biblioitems SET
3235 publicationyear = ?,
3239 collectiontitle = ?,
3241 collectionvolume= ?,
3242 editionstatement= ?,
3243 editionresponsibility = ?,
3259 my $sth = $dbh->prepare($query);
3261 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3262 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3263 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3264 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3265 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3266 $biblioitem->{'lccn'}, $biblioitem->{'marc'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'},
3267 $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort,
3268 $biblioitem->{'totalissues'}
3270 my $bibitemnum = $dbh->{'mysql_insertid'};
3272 if ( $dbh->errstr ) {
3273 $error .= "ERROR in _koha_add_biblioitem $query" . $dbh->errstr;
3277 return ( $bibitemnum, $error );
3280 =head2 _koha_delete_biblio
3282 $error = _koha_delete_biblio($dbh,$biblionumber);
3284 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3286 C<$dbh> - the database handle
3288 C<$biblionumber> - the biblionumber of the biblio to be deleted
3292 # FIXME: add error handling
3294 sub _koha_delete_biblio {
3295 my ( $dbh, $biblionumber ) = @_;
3297 # get all the data for this biblio
3298 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3299 $sth->execute($biblionumber);
3301 if ( my $data = $sth->fetchrow_hashref ) {
3303 # save the record in deletedbiblio
3304 # find the fields to save
3305 my $query = "INSERT INTO deletedbiblio SET ";
3307 foreach my $temp ( keys %$data ) {
3308 $query .= "$temp = ?,";
3309 push( @bind, $data->{$temp} );
3312 # replace the last , by ",?)"
3314 my $bkup_sth = $dbh->prepare($query);
3315 $bkup_sth->execute(@bind);
3319 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3320 $del_sth->execute($biblionumber);
3327 =head2 _koha_delete_biblioitems
3329 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3331 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3333 C<$dbh> - the database handle
3334 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3338 # FIXME: add error handling
3340 sub _koha_delete_biblioitems {
3341 my ( $dbh, $biblioitemnumber ) = @_;
3343 # get all the data for this biblioitem
3344 my $sth = $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3345 $sth->execute($biblioitemnumber);
3347 if ( my $data = $sth->fetchrow_hashref ) {
3349 # save the record in deletedbiblioitems
3350 # find the fields to save
3351 my $query = "INSERT INTO deletedbiblioitems SET ";
3353 foreach my $temp ( keys %$data ) {
3354 $query .= "$temp = ?,";
3355 push( @bind, $data->{$temp} );
3358 # replace the last , by ",?)"
3360 my $bkup_sth = $dbh->prepare($query);
3361 $bkup_sth->execute(@bind);
3364 # delete the biblioitem
3365 my $del_sth = $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3366 $del_sth->execute($biblioitemnumber);
3373 =head1 UNEXPORTED FUNCTIONS
3375 =head2 ModBiblioMarc
3377 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3379 Add MARC data for a biblio to koha
3381 Function exported, but should NOT be used, unless you really know what you're doing
3387 # pass the MARC::Record to this function, and it will create the records in the marc field
3388 my ( $record, $biblionumber, $frameworkcode ) = @_;
3389 my $dbh = C4::Context->dbh;
3390 my @fields = $record->fields();
3391 if ( !$frameworkcode ) {
3392 $frameworkcode = "";
3394 my $sth = $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3395 $sth->execute( $frameworkcode, $biblionumber );
3397 my $encoding = C4::Context->preference("marcflavour");
3399 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3400 if ( $encoding eq "UNIMARC" ) {
3401 my $string = $record->subfield( 100, "a" );
3402 if ( ($string) && ( length( $record->subfield( 100, "a" ) ) == 36 ) ) {
3403 my $f100 = $record->field(100);
3404 $record->delete_field($f100);
3406 $string = POSIX::strftime( "%Y%m%d", localtime );
3408 $string = sprintf( "%-*s", 35, $string );
3410 substr( $string, 22, 6, "frey50" );
3411 unless ( $record->subfield( 100, "a" ) ) {
3412 $record->insert_grouped_field( MARC::Field->new( 100, "", "", "a" => $string ) );
3416 #enhancement 5374: update transaction date (005) for marc21/unimarc
3417 if($encoding =~ /MARC21|UNIMARC/) {
3418 my @a= (localtime) [5,4,3,2,1,0]; $a[0]+=1900; $a[1]++;
3419 # YY MM DD HH MM SS (update year and month)
3420 my $f005= $record->field('005');
3421 $f005->update(sprintf("%4d%02d%02d%02d%02d%04.1f",@a)) if $f005;
3425 if ( C4::Context->preference("NoZebra") ) {
3427 # only NoZebra indexing needs to have
3428 # the previous version of the record
3429 $oldRecord = GetMarcBiblio($biblionumber);
3431 $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3432 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding), $biblionumber );
3434 ModZebra( $biblionumber, "specialUpdate", "biblioserver", $oldRecord, $record );
3435 return $biblionumber;
3438 =head2 z3950_extended_services
3440 z3950_extended_services($serviceType,$serviceOptions,$record);
3442 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.
3444 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3446 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3448 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3452 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3453 syntax => the record syntax (transfer syntax)
3454 databaseName = Database from connection object
3456 To set serviceOptions, call set_service_options($serviceType)
3458 C<$record> the record, if one is needed for the service type
3460 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3464 sub z3950_extended_services {
3465 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3467 # get our connection object
3468 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3470 # create a new package object
3471 my $Zpackage = $Zconn->package();
3474 $Zpackage->option( action => $action );
3476 if ( $serviceOptions->{'databaseName'} ) {
3477 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3479 if ( $serviceOptions->{'recordIdNumber'} ) {
3480 $Zpackage->option( recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3482 if ( $serviceOptions->{'recordIdOpaque'} ) {
3483 $Zpackage->option( recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3486 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3487 #if ($serviceType eq 'itemorder') {
3488 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3489 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3490 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3491 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3494 if ( $serviceOptions->{record} ) {
3495 $Zpackage->option( record => $serviceOptions->{record} );
3497 # can be xml or marc
3498 if ( $serviceOptions->{'syntax'} ) {
3499 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3503 # send the request, handle any exception encountered
3504 eval { $Zpackage->send($serviceType) };
3505 if ( $@ && $@->isa("ZOOM::Exception") ) {
3506 return "error: " . $@->code() . " " . $@->message() . "\n";
3509 # free up package resources
3510 $Zpackage->destroy();
3513 =head2 set_service_options
3515 my $serviceOptions = set_service_options($serviceType);
3517 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3519 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3523 sub set_service_options {
3524 my ($serviceType) = @_;
3527 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3528 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3530 if ( $serviceType eq 'commit' ) {
3534 if ( $serviceType eq 'create' ) {
3538 if ( $serviceType eq 'drop' ) {
3539 die "ERROR: 'drop' not currently supported (by Zebra)";
3541 return $serviceOptions;
3544 =head2 get_biblio_authorised_values
3546 find the types and values for all authorised values assigned to this biblio.
3550 MARC::Record of the bib
3552 returns: a hashref mapping the authorised value to the value set for this biblionumber
3554 $authorised_values = {
3555 'Scent' => 'flowery',
3556 'Audience' => 'Young Adult',
3557 'itemtypes' => 'SER',
3560 Notes: forlibrarian should probably be passed in, and called something different.
3564 sub get_biblio_authorised_values {
3565 my $biblionumber = shift;
3568 my $forlibrarian = 1; # are we in staff or opac?
3569 my $frameworkcode = GetFrameworkCode($biblionumber);
3571 my $authorised_values;
3573 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3574 or return $authorised_values;
3576 # assume that these entries in the authorised_value table are bibliolevel.
3577 # ones that start with 'item%' are item level.
3578 my $query = q(SELECT distinct authorised_value, kohafield
3579 FROM marc_subfield_structure
3580 WHERE authorised_value !=''
3581 AND (kohafield like 'biblio%'
3582 OR kohafield like '') );
3583 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3585 foreach my $tag ( keys(%$tagslib) ) {
3586 foreach my $subfield ( keys( %{ $tagslib->{$tag} } ) ) {
3588 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3589 if ( 'HASH' eq ref $tagslib->{$tag}{$subfield} ) {
3590 if ( defined $tagslib->{$tag}{$subfield}{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } ) {
3591 if ( defined $record->field($tag) ) {
3592 my $this_subfield_value = $record->field($tag)->subfield($subfield);
3593 if ( defined $this_subfield_value ) {
3594 $authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } = $this_subfield_value;
3602 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3603 return $authorised_values;
3612 Koha Development Team <http://koha-community.org/>
3614 Paul POULAIN paul.poulain@free.fr
3616 Joshua Ferraro jmf@liblime.com