3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Copyright 2011 Equinox Software, Inc.
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 use MARC::File::USMARC;
31 use POSIX qw(strftime);
34 use C4::Dates qw/format_date/;
35 use C4::Log; # logaction
42 use vars qw($VERSION @ISA @EXPORT);
48 @ISA = qw( Exporter );
63 &GetBiblioItemByBiblioNumber
64 &GetBiblioFromItemNumber
65 &GetBiblionumberFromItemnumber
89 &GetAuthorisedValueDesc
102 # To modify something
109 # To delete something
114 # To link headings in a bib record
115 # to authority records.
117 &LinkBibHeadingsToAuthorities
121 # those functions are exported but should not be used
122 # they are usefull is few circumstances, so are exported.
123 # but don't use them unless you're a core developer ;-)
131 &TransformHtmlToMarc2
134 &PrepareItemrecordDisplay
140 my $servers = C4::Context->config('memcached_servers');
142 require Memoize::Memcached;
143 import Memoize::Memcached qw(memoize_memcached);
146 servers => [$servers],
147 key_prefix => C4::Context->config('memcached_namespace') || 'koha',
149 memoize_memcached( 'GetMarcStructure', memcached => $memcached, expire_time => 600 ); #cache for 10 minutes
155 C4::Biblio - cataloging management functions
159 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:
163 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
165 =item 2. as raw MARC in the Zebra index and storage engine
167 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
171 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
173 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.
177 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
179 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
183 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:
187 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
189 =item 2. _koha_* - low-level internal functions for managing the koha tables
191 =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.
193 =item 4. Zebra functions used to update the Zebra index
195 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
199 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 :
203 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
205 =item 2. add the biblionumber and biblioitemnumber into the MARC records
207 =item 3. save the marc record
211 When dealing with items, we must :
215 =item 1. save the item in items table, that gives us an itemnumber
217 =item 2. add the itemnumber to the item MARC field
219 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
221 When modifying a biblio or an item, the behaviour is quite similar.
225 =head1 EXPORTED FUNCTIONS
229 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
231 Exported function (core API) for adding a new biblio to koha.
233 The first argument is a C<MARC::Record> object containing the
234 bib to add, while the second argument is the desired MARC
237 This function also accepts a third, optional argument: a hashref
238 to additional options. The only defined option is C<defer_marc_save>,
239 which if present and mapped to a true value, causes C<AddBiblio>
240 to omit the call to save the MARC in C<bibilioitems.marc>
241 and C<biblioitems.marcxml> This option is provided B<only>
242 for the use of scripts such as C<bulkmarcimport.pl> that may need
243 to do some manipulation of the MARC record for item parsing before
244 saving it and which cannot afford the performance hit of saving
245 the MARC record twice. Consequently, do not use that option
246 unless you can guarantee that C<ModBiblioMarc> will be called.
252 my $frameworkcode = shift;
253 my $options = @_ ? shift : undef;
254 my $defer_marc_save = 0;
255 if ( defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'} ) {
256 $defer_marc_save = 1;
259 my ( $biblionumber, $biblioitemnumber, $error );
260 my $dbh = C4::Context->dbh;
262 # transform the data into koha-table style data
263 SetUTF8Flag($record);
264 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
265 ( $biblionumber, $error ) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
266 $olddata->{'biblionumber'} = $biblionumber;
267 ( $biblioitemnumber, $error ) = _koha_add_biblioitem( $dbh, $olddata );
269 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
271 # update MARC subfield that stores biblioitems.cn_sort
272 _koha_marc_update_biblioitem_cn_sort( $record, $olddata, $frameworkcode );
275 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
277 logaction( "CATALOGUING", "ADD", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog");
278 return ( $biblionumber, $biblioitemnumber );
283 ModBiblio( $record,$biblionumber,$frameworkcode);
285 Replace an existing bib record identified by C<$biblionumber>
286 with one supplied by the MARC::Record object C<$record>. The embedded
287 item, biblioitem, and biblionumber fields from the previous
288 version of the bib record replace any such fields of those tags that
289 are present in C<$record>. Consequently, ModBiblio() is not
290 to be used to try to modify item records.
292 C<$frameworkcode> specifies the MARC framework to use
293 when storing the modified bib record; among other things,
294 this controls how MARC fields get mapped to display columns
295 in the C<biblio> and C<biblioitems> tables, as well as
296 which fields are used to store embedded item, biblioitem,
297 and biblionumber data for indexing.
302 my ( $record, $biblionumber, $frameworkcode ) = @_;
303 croak "No record" unless $record;
305 if ( C4::Context->preference("CataloguingLog") ) {
306 my $newrecord = GetMarcBiblio($biblionumber);
307 logaction( "CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>" . $newrecord->as_formatted );
310 # Cleaning up invalid fields must be done early or SetUTF8Flag is liable to
311 # throw an exception which probably won't be handled.
312 foreach my $field ($record->fields()) {
313 if (! $field->is_control_field()) {
314 if (scalar($field->subfields()) == 0 || (scalar($field->subfields()) == 1 && $field->subfield('9'))) {
315 $record->delete_field($field);
320 SetUTF8Flag($record);
321 my $dbh = C4::Context->dbh;
323 $frameworkcode = "" unless $frameworkcode;
325 _strip_item_fields($record, $frameworkcode);
327 # update biblionumber and biblioitemnumber in MARC
328 # FIXME - this is assuming a 1 to 1 relationship between
329 # biblios and biblioitems
330 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
331 $sth->execute($biblionumber);
332 my ($biblioitemnumber) = $sth->fetchrow;
334 _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber );
336 # load the koha-table data object
337 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
339 # update MARC subfield that stores biblioitems.cn_sort
340 _koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode );
342 # update the MARC record (that now contains biblio and items) with the new record data
343 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
345 # modify the other koha tables
346 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
347 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
351 =head2 _strip_item_fields
353 _strip_item_fields($record, $frameworkcode)
355 Utility routine to remove item tags from a
360 sub _strip_item_fields {
362 my $frameworkcode = shift;
363 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
364 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
366 # delete any item fields from incoming record to avoid
367 # duplication or incorrect data - use AddItem() or ModItem()
369 foreach my $field ( $record->field($itemtag) ) {
370 $record->delete_field($field);
374 =head2 ModBiblioframework
376 ModBiblioframework($biblionumber,$frameworkcode);
378 Exported function to modify a biblio framework
382 sub ModBiblioframework {
383 my ( $biblionumber, $frameworkcode ) = @_;
384 my $dbh = C4::Context->dbh;
385 my $sth = $dbh->prepare( "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?" );
386 $sth->execute( $frameworkcode, $biblionumber );
392 my $error = &DelBiblio($dbh,$biblionumber);
394 Exported function (core API) for deleting a biblio in koha.
395 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
396 Also backs it up to deleted* tables
397 Checks to make sure there are not issues on any of the items
399 C<$error> : undef unless an error occurs
404 my ($biblionumber) = @_;
405 my $dbh = C4::Context->dbh;
406 my $error; # for error handling
408 # First make sure this biblio has no items attached
409 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
410 $sth->execute($biblionumber);
411 if ( my $itemnumber = $sth->fetchrow ) {
413 # Fix this to use a status the template can understand
414 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
417 return $error if $error;
419 # We delete attached subscriptions
420 my $subscriptions = &C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
421 foreach my $subscription (@$subscriptions) {
422 &C4::Serials::DelSubscription( $subscription->{subscriptionid} );
425 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
426 # for at least 2 reasons :
427 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
428 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
429 # 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)
431 if ( C4::Context->preference("NoZebra") ) {
433 # only NoZebra indexing needs to have
434 # the previous version of the record
435 $oldRecord = GetMarcBiblio($biblionumber);
437 ModZebra( $biblionumber, "recordDelete", "biblioserver", $oldRecord, undef );
439 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
440 $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
441 $sth->execute($biblionumber);
442 while ( my $biblioitemnumber = $sth->fetchrow ) {
444 # delete this biblioitem
445 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
446 return $error if $error;
449 # delete biblio from Koha tables and save in deletedbiblio
450 # must do this *after* _koha_delete_biblioitems, otherwise
451 # delete cascade will prevent deletedbiblioitems rows
452 # from being generated by _koha_delete_biblioitems
453 $error = _koha_delete_biblio( $dbh, $biblionumber );
455 logaction( "CATALOGUING", "DELETE", $biblionumber, "" ) if C4::Context->preference("CataloguingLog");
460 =head2 LinkBibHeadingsToAuthorities
462 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
464 Links bib headings to authority records by checking
465 each authority-controlled field in the C<MARC::Record>
466 object C<$marc>, looking for a matching authority record,
467 and setting the linking subfield $9 to the ID of that
470 If no matching authority exists, or if multiple
471 authorities match, no $9 will be added, and any
472 existing one inthe field will be deleted.
474 Returns the number of heading links changed in the
479 sub LinkBibHeadingsToAuthorities {
482 my $num_headings_changed = 0;
483 foreach my $field ( $bib->fields() ) {
484 my $heading = C4::Heading->new_from_bib_field($field);
485 next unless defined $heading;
488 my $current_link = $field->subfield('9');
490 # look for matching authorities
491 my $authorities = $heading->authorities();
493 # want only one exact match
494 if ( $#{$authorities} == 0 ) {
495 my $authority = MARC::Record->new_from_usmarc( $authorities->[0] );
496 my $authid = $authority->field('001')->data();
497 next if defined $current_link and $current_link eq $authid;
499 $field->delete_subfield( code => '9' ) if defined $current_link;
500 $field->add_subfields( '9', $authid );
501 $num_headings_changed++;
503 if ( defined $current_link ) {
504 $field->delete_subfield( code => '9' );
505 $num_headings_changed++;
510 return $num_headings_changed;
513 =head2 GetRecordValue
515 my $values = GetRecordValue($field, $record, $frameworkcode);
517 Get MARC fields from a keyword defined in fieldmapping table.
522 my ( $field, $record, $frameworkcode ) = @_;
523 my $dbh = C4::Context->dbh;
525 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
526 $sth->execute( $frameworkcode, $field );
530 while ( my $row = $sth->fetchrow_hashref ) {
531 foreach my $field ( $record->field( $row->{fieldcode} ) ) {
532 if ( ( $row->{subfieldcode} ne "" && $field->subfield( $row->{subfieldcode} ) ) ) {
533 foreach my $subfield ( $field->subfield( $row->{subfieldcode} ) ) {
534 push @result, { 'subfield' => $subfield };
537 } elsif ( $row->{subfieldcode} eq "" ) {
538 push @result, { 'subfield' => $field->as_string() };
546 =head2 SetFieldMapping
548 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
550 Set a Field to MARC mapping value, if it already exists we don't add a new one.
554 sub SetFieldMapping {
555 my ( $framework, $field, $fieldcode, $subfieldcode ) = @_;
556 my $dbh = C4::Context->dbh;
558 my $sth = $dbh->prepare('SELECT * FROM fieldmapping WHERE fieldcode = ? AND subfieldcode = ? AND frameworkcode = ? AND field = ?');
559 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
560 if ( not $sth->fetchrow_hashref ) {
562 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
564 $sth->execute( $fieldcode, $subfieldcode, $framework, $field );
568 =head2 DeleteFieldMapping
570 DeleteFieldMapping($id);
572 Delete a field mapping from an $id.
576 sub DeleteFieldMapping {
578 my $dbh = C4::Context->dbh;
580 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
584 =head2 GetFieldMapping
586 GetFieldMapping($frameworkcode);
588 Get all field mappings for a specified frameworkcode
592 sub GetFieldMapping {
593 my ($framework) = @_;
594 my $dbh = C4::Context->dbh;
596 my $sth = $dbh->prepare('SELECT * FROM fieldmapping where frameworkcode = ?');
597 $sth->execute($framework);
600 while ( my $row = $sth->fetchrow_hashref ) {
608 $data = &GetBiblioData($biblionumber);
610 Returns information about the book with the given biblionumber.
611 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
612 the C<biblio> and C<biblioitems> tables in the
615 In addition, C<$data-E<gt>{subject}> is the list of the book's
616 subjects, separated by C<" , "> (space, comma, space).
617 If there are multiple biblioitems with the given biblionumber, only
618 the first one is considered.
624 my $dbh = C4::Context->dbh;
626 # my $query = C4::Context->preference('item-level_itypes') ?
627 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
629 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
630 # WHERE biblio.biblionumber = ?
631 # AND biblioitems.biblionumber = biblio.biblionumber
634 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
636 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
637 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
638 WHERE biblio.biblionumber = ?
639 AND biblioitems.biblionumber = biblio.biblionumber ";
641 my $sth = $dbh->prepare($query);
642 $sth->execute($bibnum);
644 $data = $sth->fetchrow_hashref;
648 } # sub GetBiblioData
650 =head2 &GetBiblioItemData
652 $itemdata = &GetBiblioItemData($biblioitemnumber);
654 Looks up the biblioitem with the given biblioitemnumber. Returns a
655 reference-to-hash. The keys are the fields from the C<biblio>,
656 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
657 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
662 sub GetBiblioItemData {
663 my ($biblioitemnumber) = @_;
664 my $dbh = C4::Context->dbh;
665 my $query = "SELECT *,biblioitems.notes AS bnotes
666 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
667 unless ( C4::Context->preference('item-level_itypes') ) {
668 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
670 $query .= " WHERE biblioitemnumber = ? ";
671 my $sth = $dbh->prepare($query);
673 $sth->execute($biblioitemnumber);
674 $data = $sth->fetchrow_hashref;
677 } # sub &GetBiblioItemData
679 =head2 GetBiblioItemByBiblioNumber
681 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
685 sub GetBiblioItemByBiblioNumber {
686 my ($biblionumber) = @_;
687 my $dbh = C4::Context->dbh;
688 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
692 $sth->execute($biblionumber);
694 while ( my $data = $sth->fetchrow_hashref ) {
695 push @results, $data;
702 =head2 GetBiblionumberFromItemnumber
707 sub GetBiblionumberFromItemnumber {
708 my ($itemnumber) = @_;
709 my $dbh = C4::Context->dbh;
710 my $sth = $dbh->prepare("Select biblionumber FROM items WHERE itemnumber = ?");
712 $sth->execute($itemnumber);
713 my ($result) = $sth->fetchrow;
717 =head2 GetBiblioFromItemNumber
719 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
721 Looks up the item with the given itemnumber. if undef, try the barcode.
723 C<&itemnodata> returns a reference-to-hash whose keys are the fields
724 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
730 sub GetBiblioFromItemNumber {
731 my ( $itemnumber, $barcode ) = @_;
732 my $dbh = C4::Context->dbh;
735 $sth = $dbh->prepare(
737 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
738 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
739 WHERE items.itemnumber = ?"
741 $sth->execute($itemnumber);
743 $sth = $dbh->prepare(
745 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
746 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
747 WHERE items.barcode = ?"
749 $sth->execute($barcode);
751 my $data = $sth->fetchrow_hashref;
758 $isbd = &GetISBDView($biblionumber);
760 Return the ISBD view which can be included in opac and intranet
765 my ( $biblionumber, $template ) = @_;
766 my $record = GetMarcBiblio($biblionumber, 1);
767 return undef unless defined $record;
768 my $itemtype = &GetFrameworkCode($biblionumber);
769 my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch", $itemtype );
770 my $tagslib = &GetMarcStructure( 1, $itemtype );
772 my $ISBD = C4::Context->preference('isbd');
777 foreach my $isbdfield ( split( /#/, $bloc ) ) {
779 # $isbdfield= /(.?.?.?)/;
780 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
781 my $fieldvalue = $1 || 0;
782 my $subfvalue = $2 || "";
784 my $analysestring = $4;
787 # warn "==> $1 / $2 / $3 / $4";
788 # my $fieldvalue=substr($isbdfield,0,3);
789 if ( $fieldvalue > 0 ) {
790 my $hasputtextbefore = 0;
791 my @fieldslist = $record->field($fieldvalue);
792 @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf );
794 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
795 # warn "FV : $fieldvalue";
796 if ( $subfvalue ne "" ) {
797 foreach my $field (@fieldslist) {
798 foreach my $subfield ( $field->subfield($subfvalue) ) {
799 my $calculated = $analysestring;
800 my $tag = $field->tag();
803 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib );
804 my $tagsubf = $tag . $subfvalue;
805 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
806 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
808 # field builded, store the result
809 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
810 $blocres .= $textbefore;
811 $hasputtextbefore = 1;
814 # remove punctuation at start
815 $calculated =~ s/^( |;|:|\.|-)*//g;
816 $blocres .= $calculated;
821 $blocres .= $textafter if $hasputtextbefore;
823 foreach my $field (@fieldslist) {
824 my $calculated = $analysestring;
825 my $tag = $field->tag();
828 my @subf = $field->subfields;
829 for my $i ( 0 .. $#subf ) {
830 my $valuecode = $subf[$i][1];
831 my $subfieldcode = $subf[$i][0];
832 my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib );
833 my $tagsubf = $tag . $subfieldcode;
835 $calculated =~ s/ # replace all {{}} codes by the value code.
836 \{\{$tagsubf\}\} # catch the {{actualcode}}
838 $valuecode # replace by the value code
841 $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
842 if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; }
845 # field builded, store the result
846 if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done
847 $blocres .= $textbefore;
848 $hasputtextbefore = 1;
851 # remove punctuation at start
852 $calculated =~ s/^( |;|:|\.|-)*//g;
853 $blocres .= $calculated;
856 $blocres .= $textafter if $hasputtextbefore;
859 $blocres .= $isbdfield;
864 $res =~ s/\{(.*?)\}//g;
866 $res =~ s/\n/<br\/>/g;
876 ( $count, @results ) = &GetBiblio($biblionumber);
881 my ($biblionumber) = @_;
882 my $dbh = C4::Context->dbh;
883 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
886 $sth->execute($biblionumber);
887 while ( my $data = $sth->fetchrow_hashref ) {
888 $results[$count] = $data;
892 return ( $count, @results );
895 =head2 GetBiblioItemInfosOf
897 GetBiblioItemInfosOf(@biblioitemnumbers);
901 sub GetBiblioItemInfosOf {
902 my @biblioitemnumbers = @_;
905 SELECT biblioitemnumber,
909 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
911 return get_infos_of( $query, 'biblioitemnumber' );
914 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
916 =head2 GetMarcStructure
918 $res = GetMarcStructure($forlibrarian,$frameworkcode);
920 Returns a reference to a big hash of hash, with the Marc structure for the given frameworkcode
921 $forlibrarian :if set to 1, the MARC descriptions are the librarians ones, otherwise it's the public (OPAC) ones
922 $frameworkcode : the framework code to read
926 # cache for results of GetMarcStructure -- needed
928 our $marc_structure_cache;
930 sub GetMarcStructure {
931 my ( $forlibrarian, $frameworkcode ) = @_;
932 my $dbh = C4::Context->dbh;
933 $frameworkcode = "" unless $frameworkcode;
935 if ( defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode} ) {
936 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
939 # my $sth = $dbh->prepare(
940 # "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
941 # $sth->execute($frameworkcode);
942 # my ($total) = $sth->fetchrow;
943 # $frameworkcode = "" unless ( $total > 0 );
944 my $sth = $dbh->prepare(
945 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
946 FROM marc_tag_structure
947 WHERE frameworkcode=?
950 $sth->execute($frameworkcode);
951 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
953 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) {
954 $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
955 $res->{$tag}->{tab} = "";
956 $res->{$tag}->{mandatory} = $mandatory;
957 $res->{$tag}->{repeatable} = $repeatable;
960 $sth = $dbh->prepare(
961 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
962 FROM marc_subfield_structure
963 WHERE frameworkcode=?
964 ORDER BY tagfield,tagsubfield
968 $sth->execute($frameworkcode);
971 my $authorised_value;
982 ( $tag, $subfield, $liblibrarian, $libopac, $tab, $mandatory, $repeatable, $authorised_value,
983 $authtypecode, $value_builder, $kohafield, $seealso, $hidden, $isurl, $link, $defaultvalue
987 $res->{$tag}->{$subfield}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
988 $res->{$tag}->{$subfield}->{tab} = $tab;
989 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
990 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
991 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
992 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
993 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
994 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
995 $res->{$tag}->{$subfield}->{seealso} = $seealso;
996 $res->{$tag}->{$subfield}->{hidden} = $hidden;
997 $res->{$tag}->{$subfield}->{isurl} = $isurl;
998 $res->{$tag}->{$subfield}->{'link'} = $link;
999 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1002 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
1007 =head2 GetUsedMarcStructure
1009 The same function as GetMarcStructure except it just takes field
1010 in tab 0-9. (used field)
1012 my $results = GetUsedMarcStructure($frameworkcode);
1014 C<$results> is a ref to an array which each case containts a ref
1015 to a hash which each keys is the columns from marc_subfield_structure
1017 C<$frameworkcode> is the framework code.
1021 sub GetUsedMarcStructure($) {
1022 my $frameworkcode = shift || '';
1025 FROM marc_subfield_structure
1027 AND frameworkcode = ?
1028 ORDER BY tagfield, tagsubfield
1030 my $sth = C4::Context->dbh->prepare($query);
1031 $sth->execute($frameworkcode);
1032 return $sth->fetchall_arrayref( {} );
1035 =head2 GetMarcFromKohaField
1037 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1039 Returns the MARC fields & subfields mapped to the koha field
1040 for the given frameworkcode
1044 sub GetMarcFromKohaField {
1045 my ( $kohafield, $frameworkcode ) = @_;
1046 return 0, 0 unless $kohafield and defined $frameworkcode;
1047 my $relations = C4::Context->marcfromkohafield;
1048 return ( $relations->{$frameworkcode}->{$kohafield}->[0], $relations->{$frameworkcode}->{$kohafield}->[1] );
1051 =head2 GetMarcBiblio
1053 my $record = GetMarcBiblio($biblionumber, [$embeditems]);
1055 Returns MARC::Record representing bib identified by
1056 C<$biblionumber>. If no bib exists, returns undef.
1057 C<$embeditems>. If set to true, items data are included.
1058 The MARC record contains biblio data, and items data if $embeditems is set to true.
1063 my $biblionumber = shift;
1064 my $embeditems = shift || 0;
1065 my $dbh = C4::Context->dbh;
1066 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1067 $sth->execute($biblionumber);
1068 my $row = $sth->fetchrow_hashref;
1069 my $marcxml = StripNonXmlChars( $row->{'marcxml'} );
1070 MARC::File::XML->default_record_format( C4::Context->preference('marcflavour') );
1071 my $record = MARC::Record->new();
1074 $record = eval { MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour') ) };
1075 if ($@) { warn " problem with :$biblionumber : $@ \n$marcxml"; }
1076 return unless $record;
1078 C4::Biblio::_koha_marc_update_bib_ids($record, '', $biblionumber, $biblionumber);
1079 C4::Biblio::EmbedItemsInMarcBiblio($record, $biblionumber) if ($embeditems);
1089 my $marcxml = GetXmlBiblio($biblionumber);
1091 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1092 The XML contains both biblio & item datas
1097 my ($biblionumber) = @_;
1098 my $dbh = C4::Context->dbh;
1099 my $sth = $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1100 $sth->execute($biblionumber);
1101 my ($marcxml) = $sth->fetchrow;
1105 =head2 GetCOinSBiblio
1107 my $coins = GetCOinSBiblio($biblionumber);
1109 Returns the COinS(a span) which can be included in a biblio record
1113 sub GetCOinSBiblio {
1114 my ($biblionumber) = @_;
1115 my $record = GetMarcBiblio($biblionumber);
1117 # get the coin format
1119 # can't get a valid MARC::Record object, bail out at this point
1120 warn "We called GetMarcBiblio with a biblionumber that doesn't exist biblionumber=$biblionumber";
1123 my $pos7 = substr $record->leader(), 7, 1;
1124 my $pos6 = substr $record->leader(), 6, 1;
1127 my ( $aulast, $aufirst ) = ( '', '' );
1136 my $titletype = 'b';
1138 # For the purposes of generating COinS metadata, LDR/06-07 can be
1139 # considered the same for UNIMARC and MARC21
1144 'b' => 'manuscript',
1146 'd' => 'manuscript',
1150 'i' => 'audioRecording',
1151 'j' => 'audioRecording',
1154 'm' => 'computerProgram',
1159 'a' => 'journalArticle',
1163 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book';
1165 if ( $genre eq 'book' ) {
1166 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1169 ##### We must transform mtx to a valable mtx and document type ####
1170 if ( $genre eq 'book' ) {
1172 } elsif ( $genre eq 'journal' ) {
1175 } elsif ( $genre eq 'journalArticle' ) {
1183 $genre = ( $mtx eq 'dc' ) ? "&rft.type=$genre" : "&rft.genre=$genre";
1185 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
1188 $aulast = $record->subfield( '700', 'a' ) || '';
1189 $aufirst = $record->subfield( '700', 'b' ) || '';
1190 $oauthors = "&rft.au=$aufirst $aulast";
1193 if ( $record->field('200') ) {
1194 for my $au ( $record->field('200')->subfield('g') ) {
1195 $oauthors .= "&rft.au=$au";
1200 ? "&rft.title=" . $record->subfield( '200', 'a' )
1201 : "&rft.title=" . $record->subfield( '200', 'a' ) . "&rft.btitle=" . $record->subfield( '200', 'a' );
1202 $pubyear = $record->subfield( '210', 'd' ) || '';
1203 $publisher = $record->subfield( '210', 'c' ) || '';
1204 $isbn = $record->subfield( '010', 'a' ) || '';
1205 $issn = $record->subfield( '011', 'a' ) || '';
1208 # MARC21 need some improve
1211 if ( $record->field('100') ) {
1212 $oauthors .= "&rft.au=" . $record->subfield( '100', 'a' );
1216 if ( $record->field('700') ) {
1217 for my $au ( $record->field('700')->subfield('a') ) {
1218 $oauthors .= "&rft.au=$au";
1221 $title = "&rft." . $titletype . "title=" . $record->subfield( '245', 'a' );
1222 $subtitle = $record->subfield( '245', 'b' ) || '';
1223 $title .= $subtitle;
1224 if ($titletype eq 'a') {
1225 $pubyear = $record->field('008') || '';
1226 $pubyear = substr($pubyear->data(), 7, 4) if $pubyear;
1227 $isbn = $record->subfield( '773', 'z' ) || '';
1228 $issn = $record->subfield( '773', 'x' ) || '';
1229 if ($mtx eq 'journal') {
1230 $title .= "&rft.title=" . (($record->subfield( '773', 't' ) || $record->subfield( '773', 'a')));
1232 $title .= "&rft.btitle=" . (($record->subfield( '773', 't' ) || $record->subfield( '773', 'a')) || '');
1234 foreach my $rel ($record->subfield( '773', 'g' )) {
1241 $pubyear = $record->subfield( '260', 'c' ) || '';
1242 $publisher = $record->subfield( '260', 'b' ) || '';
1243 $isbn = $record->subfield( '020', 'a' ) || '';
1244 $issn = $record->subfield( '022', 'a' ) || '';
1249 "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";
1250 $coins_value =~ s/(\ |&[^a])/\+/g;
1251 $coins_value =~ s/\"/\"\;/g;
1253 #<!-- 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="
1255 return $coins_value;
1261 return the prices in accordance with the Marc format.
1265 my ( $record, $marcflavour ) = @_;
1269 if ( $marcflavour eq "MARC21" ) {
1270 @listtags = ('345', '020');
1272 } elsif ( $marcflavour eq "UNIMARC" ) {
1273 @listtags = ('345', '010');
1279 for my $field ( $record->field(@listtags) ) {
1280 for my $subfield_value ($field->subfield($subfield)){
1282 return $subfield_value if ($subfield_value);
1285 return 0; # no price found
1288 =head2 GetMarcQuantity
1290 return the quantity of a book. Used in acquisition only, when importing a file an iso2709 from a bookseller
1291 Warning : this is not really in the marc standard. In Unimarc, Electre (the most widely used bookseller) use the 969$a
1295 sub GetMarcQuantity {
1296 my ( $record, $marcflavour ) = @_;
1300 if ( $marcflavour eq "MARC21" ) {
1302 } elsif ( $marcflavour eq "UNIMARC" ) {
1303 @listtags = ('969');
1309 for my $field ( $record->field(@listtags) ) {
1310 for my $subfield_value ($field->subfield($subfield)){
1312 if ($subfield_value) {
1313 # in France, the cents separator is the , but sometimes, ppl use a .
1314 # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
1315 $subfield_value =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
1316 return $subfield_value;
1320 return 0; # no price found
1324 =head2 GetAuthorisedValueDesc
1326 my $subfieldvalue =get_authorised_value_desc(
1327 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category, $opac);
1329 Retrieve the complete description for a given authorised value.
1331 Now takes $category and $value pair too.
1333 my $auth_value_desc =GetAuthorisedValueDesc(
1334 '','', 'DVD' ,'','','CCODE');
1336 If the optional $opac parameter is set to a true value, displays OPAC
1337 descriptions rather than normal ones when they exist.
1341 sub GetAuthorisedValueDesc {
1342 my ( $tag, $subfield, $value, $framework, $tagslib, $category, $opac ) = @_;
1343 my $dbh = C4::Context->dbh;
1347 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1350 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1351 return C4::Branch::GetBranchName($value);
1355 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1356 return getitemtypeinfo($value)->{description};
1359 #---- "true" authorized value
1360 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1363 if ( $category ne "" ) {
1364 my $sth = $dbh->prepare( "SELECT lib, lib_opac FROM authorised_values WHERE category = ? AND authorised_value = ?" );
1365 $sth->execute( $category, $value );
1366 my $data = $sth->fetchrow_hashref;
1367 return ( $opac && $data->{'lib_opac'} ) ? $data->{'lib_opac'} : $data->{'lib'};
1369 return $value; # if nothing is found return the original value
1373 =head2 GetMarcControlnumber
1375 $marccontrolnumber = GetMarcControlnumber($record,$marcflavour);
1377 Get the control number / record Identifier from the MARC record and return it.
1381 sub GetMarcControlnumber {
1382 my ( $record, $marcflavour ) = @_;
1383 my $controlnumber = "";
1384 # Control number or Record identifier are the same field in MARC21 and UNIMARC
1385 # Keep $marcflavour for possible later use
1386 if ($marcflavour eq "MARC21" || $marcflavour eq "UNIMARC") {
1387 my $controlnumberField = $record->field('001');
1388 if ($controlnumberField) {
1389 $controlnumber = $controlnumberField->data();
1392 return $controlnumber;
1397 $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
1399 Get all ISBNs from the MARC record and returns them in an array.
1400 ISBNs stored in differents places depending on MARC flavour
1405 my ( $record, $marcflavour ) = @_;
1407 if ( $marcflavour eq "UNIMARC" ) {
1409 } else { # assume marc21 if not unimarc
1416 foreach my $field ( $record->field($scope) ) {
1417 my $value = $field->as_string();
1418 if ( $isbn ne "" ) {
1419 $marcisbn = { marcisbn => $isbn, };
1420 push @marcisbns, $marcisbn;
1423 if ( $isbn ne $value ) {
1424 $isbn = $isbn . " " . $value;
1429 $marcisbn = { marcisbn => $isbn };
1430 push @marcisbns, $marcisbn; #load last tag into array
1437 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1439 Get all notes from the MARC record and returns them in an array.
1440 The note are stored in differents places depending on MARC flavour
1445 my ( $record, $marcflavour ) = @_;
1447 if ( $marcflavour eq "UNIMARC" ) {
1449 } else { # assume marc21 if not unimarc
1456 foreach my $field ( $record->field($scope) ) {
1457 my $value = $field->as_string();
1458 if ( $note ne "" ) {
1459 $marcnote = { marcnote => $note, };
1460 push @marcnotes, $marcnote;
1463 if ( $note ne $value ) {
1464 $note = $note . " " . $value;
1469 $marcnote = { marcnote => $note };
1470 push @marcnotes, $marcnote; #load last tag into array
1473 } # end GetMarcNotes
1475 =head2 GetMarcSubjects
1477 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1479 Get all subjects from the MARC record and returns them in an array.
1480 The subjects are stored in differents places depending on MARC flavour
1484 sub GetMarcSubjects {
1485 my ( $record, $marcflavour ) = @_;
1486 my ( $mintag, $maxtag );
1487 if ( $marcflavour eq "UNIMARC" ) {
1490 } else { # assume marc21 if not unimarc
1500 my $subject_limit = C4::Context->preference("TraceCompleteSubfields") ? 'su,complete-subfield' : 'su';
1502 foreach my $field ( $record->field('6..') ) {
1503 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1505 my @subfields = $field->subfields();
1509 # if there is an authority link, build the link with an= subfield9
1511 for my $subject_subfield (@subfields) {
1513 # don't load unimarc subfields 3,4,5
1514 next if ( ( $marcflavour eq "UNIMARC" ) and ( $subject_subfield->[0] =~ /2|3|4|5/ ) );
1516 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1517 next if ( ( $marcflavour eq "MARC21" ) and ( $subject_subfield->[0] =~ /2/ ) );
1518 my $code = $subject_subfield->[0];
1519 my $value = $subject_subfield->[1];
1520 my $linkvalue = $value;
1521 $linkvalue =~ s/(\(|\))//g;
1523 if ( $counter != 0 ) {
1524 $operator = ' and ';
1528 @link_loop = ( { 'limit' => 'an', link => "$linkvalue" } );
1530 if ( not $found9 ) {
1531 push @link_loop, { 'limit' => $subject_limit, link => $linkvalue, operator => $operator };
1534 if ( $counter != 0 ) {
1535 $separator = C4::Context->preference('authoritysep');
1539 my @this_link_loop = @link_loop;
1540 push @subfields_loop, { code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator } unless ( $subject_subfield->[0] eq 9 );
1544 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1547 return \@marcsubjects;
1548 } #end getMARCsubjects
1550 =head2 GetMarcAuthors
1552 authors = GetMarcAuthors($record,$marcflavour);
1554 Get all authors from the MARC record and returns them in an array.
1555 The authors are stored in differents places depending on MARC flavour
1559 sub GetMarcAuthors {
1560 my ( $record, $marcflavour ) = @_;
1561 my ( $mintag, $maxtag );
1563 # tagslib useful for UNIMARC author reponsabilities
1565 &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.
1566 if ( $marcflavour eq "UNIMARC" ) {
1569 } elsif ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) { # assume marc21 or normarc if not unimarc
1577 foreach my $field ( $record->fields ) {
1578 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1581 my @subfields = $field->subfields();
1584 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1585 my $subfield9 = $field->subfield('9');
1586 for my $authors_subfield (@subfields) {
1588 # don't load unimarc subfields 3, 5
1589 next if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /3|5/ ) );
1590 my $subfieldcode = $authors_subfield->[0];
1591 my $value = $authors_subfield->[1];
1592 my $linkvalue = $value;
1593 $linkvalue =~ s/(\(|\))//g;
1595 if ( $count_auth != 0 ) {
1596 $operator = ' and ';
1599 # if we have an authority link, use that as the link, otherwise use standard searching
1601 @link_loop = ( { 'limit' => 'an', link => "$subfield9" } );
1604 # reset $linkvalue if UNIMARC author responsibility
1605 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] eq "4" ) ) {
1606 $linkvalue = "(" . GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) . ")";
1608 push @link_loop, { 'limit' => 'au', link => $linkvalue, operator => $operator };
1610 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib )
1611 if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /4/ ) );
1612 my @this_link_loop = @link_loop;
1614 if ( $count_auth != 0 ) {
1615 $separator = C4::Context->preference('authoritysep');
1617 push @subfields_loop,
1618 { code => $subfieldcode,
1620 link_loop => \@this_link_loop,
1621 separator => $separator
1623 unless ( $authors_subfield->[0] eq '9' );
1626 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1628 return \@marcauthors;
1633 $marcurls = GetMarcUrls($record,$marcflavour);
1635 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1636 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1641 my ( $record, $marcflavour ) = @_;
1644 for my $field ( $record->field('856') ) {
1646 for my $note ( $field->subfield('z') ) {
1647 push @notes, { note => $note };
1649 my @urls = $field->subfield('u');
1650 foreach my $url (@urls) {
1652 if ( $marcflavour eq 'MARC21' ) {
1653 my $s3 = $field->subfield('3');
1654 my $link = $field->subfield('y');
1655 unless ( $url =~ /^\w+:/ ) {
1656 if ( $field->indicator(1) eq '7' ) {
1657 $url = $field->subfield('2') . "://" . $url;
1658 } elsif ( $field->indicator(1) eq '1' ) {
1659 $url = 'ftp://' . $url;
1662 # properly, this should be if ind1=4,
1663 # however we will assume http protocol since we're building a link.
1664 $url = 'http://' . $url;
1668 # TODO handle ind 2 (relationship)
1673 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1674 $marcurl->{'part'} = $s3 if ($link);
1675 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ );
1677 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1678 $marcurl->{'MARCURL'} = $url;
1680 push @marcurls, $marcurl;
1686 =head2 GetMarcSeries
1688 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1690 Get all series from the MARC record and returns them in an array.
1691 The series are stored in differents places depending on MARC flavour
1696 my ( $record, $marcflavour ) = @_;
1697 my ( $mintag, $maxtag );
1698 if ( $marcflavour eq "UNIMARC" ) {
1701 } else { # assume marc21 if not unimarc
1711 foreach my $field ( $record->field('440'), $record->field('490') ) {
1714 #my $value = $field->subfield('a');
1715 #$marcsubjct = {MARCSUBJCT => $value,};
1716 my @subfields = $field->subfields();
1718 #warn "subfields:".join " ", @$subfields;
1721 for my $series_subfield (@subfields) {
1723 undef $volume_number;
1725 # see if this is an instance of a volume
1726 if ( $series_subfield->[0] eq 'v' ) {
1730 my $code = $series_subfield->[0];
1731 my $value = $series_subfield->[1];
1732 my $linkvalue = $value;
1733 $linkvalue =~ s/(\(|\))//g;
1734 if ( $counter != 0 ) {
1735 push @link_loop, { link => $linkvalue, operator => ' and ', };
1737 push @link_loop, { link => $linkvalue, operator => undef, };
1740 if ( $counter != 0 ) {
1741 $separator = C4::Context->preference('authoritysep');
1743 if ($volume_number) {
1744 push @subfields_loop, { volumenum => $value };
1746 if ( $series_subfield->[0] ne '9' ) {
1747 push @subfields_loop, {
1750 link_loop => \@link_loop,
1751 separator => $separator,
1752 volumenum => $volume_number,
1758 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1760 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1761 #push @marcsubjcts, $marcsubjct;
1765 my $marcseriessarray = \@marcseries;
1766 return $marcseriessarray;
1767 } #end getMARCseriess
1771 $marchostsarray = GetMarcHosts($record,$marcflavour);
1773 Get all host records (773s MARC21, 461 UNIMARC) from the MARC record and returns them in an array.
1778 my ( $record, $marcflavour ) = @_;
1779 my ( $tag,$title_subf,$bibnumber_subf,$itemnumber_subf);
1780 $marcflavour ||="MARC21";
1781 if ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) {
1784 $bibnumber_subf ="0";
1785 $itemnumber_subf='9';
1787 elsif ($marcflavour eq "UNIMARC") {
1790 $bibnumber_subf ="0";
1791 $itemnumber_subf='9';
1796 foreach my $field ( $record->field($tag)) {
1800 my $hostbiblionumber = $field->subfield("$bibnumber_subf");
1801 my $hosttitle = $field->subfield($title_subf);
1802 my $hostitemnumber=$field->subfield($itemnumber_subf);
1803 push @fields_loop, { hostbiblionumber => $hostbiblionumber, hosttitle => $hosttitle, hostitemnumber => $hostitemnumber};
1804 push @marchosts, { MARCHOSTS_FIELDS_LOOP => \@fields_loop };
1807 my $marchostsarray = \@marchosts;
1808 return $marchostsarray;
1811 =head2 GetFrameworkCode
1813 $frameworkcode = GetFrameworkCode( $biblionumber )
1817 sub GetFrameworkCode {
1818 my ($biblionumber) = @_;
1819 my $dbh = C4::Context->dbh;
1820 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1821 $sth->execute($biblionumber);
1822 my ($frameworkcode) = $sth->fetchrow;
1823 return $frameworkcode;
1826 =head2 TransformKohaToMarc
1828 $record = TransformKohaToMarc( $hash )
1830 This function builds partial MARC::Record from a hash
1831 Hash entries can be from biblio or biblioitems.
1833 This function is called in acquisition module, to create a basic catalogue entry from user entry
1837 sub TransformKohaToMarc {
1839 my $sth = C4::Context->dbh->prepare( "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?" );
1840 my $record = MARC::Record->new();
1841 SetMarcUnicodeFlag( $record, C4::Context->preference("marcflavour") );
1842 foreach ( keys %{$hash} ) {
1843 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1848 =head2 PrepHostMarcField
1850 $hostfield = PrepHostMarcField ( $hostbiblionumber,$hostitemnumber,$marcflavour )
1852 This function returns a host field populated with data from the host record, the field can then be added to an analytical record
1856 sub PrepHostMarcField {
1857 my ($hostbiblionumber,$hostitemnumber, $marcflavour) = @_;
1858 $marcflavour ||="MARC21";
1860 my $hostrecord = GetMarcBiblio($hostbiblionumber);
1861 my $item = C4::Items::GetItem($hostitemnumber);
1864 if ( $marcflavour eq "MARC21" || $marcflavour eq "NORMARC" ) {
1868 if ($hostrecord->subfield('100','a')){
1869 $mainentry = $hostrecord->subfield('100','a');
1870 } elsif ($hostrecord->subfield('110','a')){
1871 $mainentry = $hostrecord->subfield('110','a');
1873 $mainentry = $hostrecord->subfield('111','a');
1876 # qualification info
1878 if (my $field260 = $hostrecord->field('260')){
1879 $qualinfo = $field260->as_string( 'abc' );
1884 my $ed = $hostrecord->subfield('250','a');
1885 my $barcode = $item->{'barcode'};
1886 my $title = $hostrecord->subfield('245','a');
1888 # record control number, 001 with 003 and prefix
1890 if ($hostrecord->field('001')){
1891 $recctrlno = $hostrecord->field('001')->data();
1892 if ($hostrecord->field('003')){
1893 $recctrlno = '('.$hostrecord->field('003')->data().')'.$recctrlno;
1898 my $issn = $hostrecord->subfield('022','a');
1899 my $isbn = $hostrecord->subfield('020','a');
1902 $hostmarcfield = MARC::Field->new(
1904 '0' => $hostbiblionumber,
1905 '9' => $hostitemnumber,
1915 } elsif ($marcflavour eq "UNIMARC") {
1916 $hostmarcfield = MARC::Field->new(
1918 '0' => $hostbiblionumber,
1919 't' => $hostrecord->subfield('200','a'),
1920 '9' => $hostitemnumber
1924 return $hostmarcfield;
1928 =head2 TransformKohaToMarcOneField
1930 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1934 sub TransformKohaToMarcOneField {
1935 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1936 $frameworkcode = '' unless $frameworkcode;
1940 if ( !defined $sth ) {
1941 my $dbh = C4::Context->dbh;
1942 $sth = $dbh->prepare( "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?" );
1944 $sth->execute( $frameworkcode, $kohafieldname );
1945 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1946 my @values = split(/\s?\|\s?/, $value, -1);
1948 foreach my $itemvalue (@values){
1949 my $tag = $record->field($tagfield);
1951 $tag->add_subfields( $tagsubfield => $itemvalue );
1952 $record->delete_field($tag);
1953 $record->insert_fields_ordered($tag);
1956 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $itemvalue );
1963 =head2 TransformHtmlToXml
1965 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator,
1966 $ind_tag, $auth_type )
1968 $auth_type contains :
1972 =item - nothing : rebuild a biblio. In UNIMARC the encoding is in 100$a pos 26/27
1974 =item - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1976 =item - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1982 sub TransformHtmlToXml {
1983 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1984 my $xml = MARC::File::XML::header('UTF-8');
1985 $xml .= "<record>\n";
1986 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1987 MARC::File::XML->default_record_format($auth_type);
1989 # in UNIMARC, field 100 contains the encoding
1990 # check that there is one, otherwise the
1991 # MARC::Record->new_from_xml will fail (and Koha will die)
1992 my $unimarc_and_100_exist = 0;
1993 $unimarc_and_100_exist = 1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1998 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
2000 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a" ) {
2002 # if we have a 100 field and it's values are not correct, skip them.
2003 # if we don't have any valid 100 field, we will create a default one at the end
2004 my $enc = substr( @$values[$i], 26, 2 );
2005 if ( $enc eq '01' or $enc eq '50' or $enc eq '03' ) {
2006 $unimarc_and_100_exist = 1;
2011 @$values[$i] =~ s/&/&/g;
2012 @$values[$i] =~ s/</</g;
2013 @$values[$i] =~ s/>/>/g;
2014 @$values[$i] =~ s/"/"/g;
2015 @$values[$i] =~ s/'/'/g;
2017 # if ( !utf8::is_utf8( @$values[$i] ) ) {
2018 # utf8::decode( @$values[$i] );
2020 if ( ( @$tags[$i] ne $prevtag ) ) {
2021 $j++ unless ( @$tags[$i] eq "" );
2022 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
2023 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
2024 my $ind1 = _default_ind_to_space($indicator1);
2026 if ( @$indicator[$j] ) {
2027 $ind2 = _default_ind_to_space($indicator2);
2029 warn "Indicator in @$tags[$i] is empty";
2033 $xml .= "</datafield>\n";
2034 if ( ( @$tags[$i] && @$tags[$i] > 10 )
2035 && ( @$values[$i] ne "" ) ) {
2036 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2037 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2043 if ( @$values[$i] ne "" ) {
2046 if ( @$tags[$i] eq "000" ) {
2047 $xml .= "<leader>@$values[$i]</leader>\n";
2050 # rest of the fixed fields
2051 } elsif ( @$tags[$i] < 10 ) {
2052 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
2055 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2056 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2061 } else { # @$tags[$i] eq $prevtag
2062 my $indicator1 = eval { substr( @$indicator[$j], 0, 1 ) };
2063 my $indicator2 = eval { substr( @$indicator[$j], 1, 1 ) };
2064 my $ind1 = _default_ind_to_space($indicator1);
2066 if ( @$indicator[$j] ) {
2067 $ind2 = _default_ind_to_space($indicator2);
2069 warn "Indicator in @$tags[$i] is empty";
2072 if ( @$values[$i] eq "" ) {
2075 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
2078 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
2081 $prevtag = @$tags[$i];
2083 $xml .= "</datafield>\n" if @$tags > 0;
2084 if ( C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist ) {
2086 # warn "SETTING 100 for $auth_type";
2087 my $string = strftime( "%Y%m%d", localtime(time) );
2089 # set 50 to position 26 is biblios, 13 if authorities
2091 $pos = 13 if $auth_type eq 'UNIMARCAUTH';
2092 $string = sprintf( "%-*s", 35, $string );
2093 substr( $string, $pos, 6, "50" );
2094 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
2095 $xml .= "<subfield code=\"a\">$string</subfield>\n";
2096 $xml .= "</datafield>\n";
2098 $xml .= "</record>\n";
2099 $xml .= MARC::File::XML::footer();
2103 =head2 _default_ind_to_space
2105 Passed what should be an indicator returns a space
2106 if its undefined or zero length
2110 sub _default_ind_to_space {
2112 if ( !defined $s || $s eq q{} ) {
2118 =head2 TransformHtmlToMarc
2120 L<$record> = TransformHtmlToMarc(L<$cgi>)
2121 L<$cgi> is the CGI object which containts the values for subfields
2123 'tag_010_indicator1_531951' ,
2124 'tag_010_indicator2_531951' ,
2125 'tag_010_code_a_531951_145735' ,
2126 'tag_010_subfield_a_531951_145735' ,
2127 'tag_200_indicator1_873510' ,
2128 'tag_200_indicator2_873510' ,
2129 'tag_200_code_a_873510_673465' ,
2130 'tag_200_subfield_a_873510_673465' ,
2131 'tag_200_code_b_873510_704318' ,
2132 'tag_200_subfield_b_873510_704318' ,
2133 'tag_200_code_e_873510_280822' ,
2134 'tag_200_subfield_e_873510_280822' ,
2135 'tag_200_code_f_873510_110730' ,
2136 'tag_200_subfield_f_873510_110730' ,
2138 L<$record> is the MARC::Record object.
2142 sub TransformHtmlToMarc {
2145 my @params = $cgi->param();
2147 # explicitly turn on the UTF-8 flag for all
2148 # 'tag_' parameters to avoid incorrect character
2149 # conversion later on
2150 my $cgi_params = $cgi->Vars;
2151 foreach my $param_name ( keys %$cgi_params ) {
2152 if ( $param_name =~ /^tag_/ ) {
2153 my $param_value = $cgi_params->{$param_name};
2154 if ( utf8::decode($param_value) ) {
2155 $cgi_params->{$param_name} = $param_value;
2158 # FIXME - need to do something if string is not valid UTF-8
2162 # creating a new record
2163 my $record = MARC::Record->new();
2166 while ( $params[$i] ) { # browse all CGI params
2167 my $param = $params[$i];
2170 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
2171 if ( $param eq 'biblionumber' ) {
2172 my ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField( "biblio.biblionumber", '' );
2173 if ( $biblionumbertagfield < 10 ) {
2174 $newfield = MARC::Field->new( $biblionumbertagfield, $cgi->param($param), );
2176 $newfield = MARC::Field->new( $biblionumbertagfield, '', '', "$biblionumbertagsubfield" => $cgi->param($param), );
2178 push @fields, $newfield if ($newfield);
2179 } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..."
2182 my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) );
2183 my $ind2 = _default_ind_to_space( substr( $cgi->param( $params[ $i + 1 ] ), 0, 1 ) );
2187 if ( $tag < 10 ) { # no code for theses fields
2188 # in MARC editor, 000 contains the leader.
2189 if ( $tag eq '000' ) {
2190 # Force a fake leader even if not provided to avoid crashing
2191 # during decoding MARC record containing UTF-8 characters
2193 length( $cgi->param($params[$j+1]) ) == 24
2194 ? $cgi->param( $params[ $j + 1 ] )
2198 # between 001 and 009 (included)
2199 } elsif ( $cgi->param( $params[ $j + 1 ] ) ne '' ) {
2200 $newfield = MARC::Field->new( $tag, $cgi->param( $params[ $j + 1 ] ), );
2203 # > 009, deal with subfields
2205 while ( defined $params[$j] && $params[$j] =~ /_code_/ ) { # browse all it's subfield
2206 my $inner_param = $params[$j];
2208 if ( $cgi->param( $params[ $j + 1 ] ) ne '' ) { # only if there is a value (code => value)
2209 $newfield->add_subfields( $cgi->param($inner_param) => $cgi->param( $params[ $j + 1 ] ) );
2212 if ( $cgi->param( $params[ $j + 1 ] ) ne '' ) { # creating only if there is a value (code => value)
2213 $newfield = MARC::Field->new( $tag, $ind1, $ind2, $cgi->param($inner_param) => $cgi->param( $params[ $j + 1 ] ), );
2219 push @fields, $newfield if ($newfield);
2224 $record->append_fields(@fields);
2228 # cache inverted MARC field map
2229 our $inverted_field_map;
2231 =head2 TransformMarcToKoha
2233 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
2235 Extract data from a MARC bib record into a hashref representing
2236 Koha biblio, biblioitems, and items fields.
2240 sub TransformMarcToKoha {
2241 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
2244 $limit_table = $limit_table || 0;
2245 $frameworkcode = '' unless defined $frameworkcode;
2247 unless ( defined $inverted_field_map ) {
2248 $inverted_field_map = _get_inverted_marc_field_map();
2252 if ( defined $limit_table && $limit_table eq 'items' ) {
2253 $tables{'items'} = 1;
2255 $tables{'items'} = 1;
2256 $tables{'biblio'} = 1;
2257 $tables{'biblioitems'} = 1;
2260 # traverse through record
2261 MARCFIELD: foreach my $field ( $record->fields() ) {
2262 my $tag = $field->tag();
2263 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2264 if ( $field->is_control_field() ) {
2265 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2266 ENTRY: foreach my $entry ( @{$kohafields} ) {
2267 my ( $subfield, $table, $column ) = @{$entry};
2268 next ENTRY unless exists $tables{$table};
2269 my $key = _disambiguate( $table, $column );
2270 if ( $result->{$key} ) {
2271 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $field->data() eq "" ) ) {
2272 $result->{$key} .= " | " . $field->data();
2275 $result->{$key} = $field->data();
2280 # deal with subfields
2281 MARCSUBFIELD: foreach my $sf ( $field->subfields() ) {
2282 my $code = $sf->[0];
2283 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2284 my $value = $sf->[1];
2285 SFENTRY: foreach my $entry ( @{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} } ) {
2286 my ( $table, $column ) = @{$entry};
2287 next SFENTRY unless exists $tables{$table};
2288 my $key = _disambiguate( $table, $column );
2289 if ( $result->{$key} ) {
2290 unless ( ( $key eq "biblionumber" or $key eq "biblioitemnumber" ) and ( $value eq "" ) ) {
2291 $result->{$key} .= " | " . $value;
2294 $result->{$key} = $value;
2301 # modify copyrightdate to keep only the 1st year found
2302 if ( exists $result->{'copyrightdate'} ) {
2303 my $temp = $result->{'copyrightdate'};
2304 $temp =~ m/c(\d\d\d\d)/;
2305 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2306 $result->{'copyrightdate'} = $1;
2307 } else { # if no cYYYY, get the 1st date.
2308 $temp =~ m/(\d\d\d\d)/;
2309 $result->{'copyrightdate'} = $1;
2313 # modify publicationyear to keep only the 1st year found
2314 if ( exists $result->{'publicationyear'} ) {
2315 my $temp = $result->{'publicationyear'};
2316 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2317 $result->{'publicationyear'} = $1;
2318 } else { # if no cYYYY, get the 1st date.
2319 $temp =~ m/(\d\d\d\d)/;
2320 $result->{'publicationyear'} = $1;
2327 sub _get_inverted_marc_field_map {
2329 my $relations = C4::Context->marcfromkohafield;
2331 foreach my $frameworkcode ( keys %{$relations} ) {
2332 foreach my $kohafield ( keys %{ $relations->{$frameworkcode} } ) {
2333 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2334 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2335 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2336 my ( $table, $column ) = split /[.]/, $kohafield, 2;
2337 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2338 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2344 =head2 _disambiguate
2346 $newkey = _disambiguate($table, $field);
2348 This is a temporary hack to distinguish between the
2349 following sets of columns when using TransformMarcToKoha.
2351 items.cn_source & biblioitems.cn_source
2352 items.cn_sort & biblioitems.cn_sort
2354 Columns that are currently NOT distinguished (FIXME
2355 due to lack of time to fully test) are:
2357 biblio.notes and biblioitems.notes
2362 FIXME - this is necessary because prefixing each column
2363 name with the table name would require changing lots
2364 of code and templates, and exposing more of the DB
2365 structure than is good to the UI templates, particularly
2366 since biblio and bibloitems may well merge in a future
2367 version. In the future, it would also be good to
2368 separate DB access and UI presentation field names
2373 sub CountItemsIssued {
2374 my ($biblionumber) = @_;
2375 my $dbh = C4::Context->dbh;
2376 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2377 $sth->execute($biblionumber);
2378 my $row = $sth->fetchrow_hashref();
2379 return $row->{'issuedCount'};
2383 my ( $table, $column ) = @_;
2384 if ( $column eq "cn_sort" or $column eq "cn_source" ) {
2385 return $table . '.' . $column;
2392 =head2 get_koha_field_from_marc
2394 $result->{_disambiguate($table, $field)} =
2395 get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2397 Internal function to map data from the MARC record to a specific non-MARC field.
2398 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2402 sub get_koha_field_from_marc {
2403 my ( $koha_table, $koha_column, $record, $frameworkcode ) = @_;
2404 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table . '.' . $koha_column, $frameworkcode );
2406 foreach my $field ( $record->field($tagfield) ) {
2407 if ( $field->tag() < 10 ) {
2409 $kohafield .= " | " . $field->data();
2411 $kohafield = $field->data();
2414 if ( $field->subfields ) {
2415 my @subfields = $field->subfields();
2416 foreach my $subfieldcount ( 0 .. $#subfields ) {
2417 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2419 $kohafield .= " | " . $subfields[$subfieldcount][1];
2421 $kohafield = $subfields[$subfieldcount][1];
2431 =head2 TransformMarcToKohaOneField
2433 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2437 sub TransformMarcToKohaOneField {
2439 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2440 # only the 1st will be retrieved...
2441 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2443 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $kohatable . "." . $kohafield, $frameworkcode );
2444 foreach my $field ( $record->field($tagfield) ) {
2445 if ( $field->tag() < 10 ) {
2446 if ( $result->{$kohafield} ) {
2447 $result->{$kohafield} .= " | " . $field->data();
2449 $result->{$kohafield} = $field->data();
2452 if ( $field->subfields ) {
2453 my @subfields = $field->subfields();
2454 foreach my $subfieldcount ( 0 .. $#subfields ) {
2455 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2456 if ( $result->{$kohafield} ) {
2457 $result->{$kohafield} .= " | " . $subfields[$subfieldcount][1];
2459 $result->{$kohafield} = $subfields[$subfieldcount][1];
2469 =head1 OTHER FUNCTIONS
2472 =head2 PrepareItemrecordDisplay
2474 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2476 Returns a hash with all the fields for Display a given item data in a template
2478 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2482 sub PrepareItemrecordDisplay {
2484 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2486 my $dbh = C4::Context->dbh;
2487 $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2488 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2489 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2491 # return nothing if we don't have found an existing framework.
2492 return q{} unless $tagslib;
2495 $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2498 my $authorised_values_sth = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib" );
2499 foreach my $tag ( sort keys %{$tagslib} ) {
2500 my $previous_tag = '';
2503 # loop through each subfield
2505 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2506 next if ( subfield_is_koha_internal_p($subfield) );
2507 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2509 $subfield_data{tag} = $tag;
2510 $subfield_data{subfield} = $subfield;
2511 $subfield_data{countsubfield} = $cntsubf++;
2512 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2514 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2515 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2516 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2517 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2518 $subfield_data{hidden} = "display:none"
2519 if $tagslib->{$tag}->{$subfield}->{hidden};
2520 my ( $x, $defaultvalue );
2522 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2524 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2525 if ( !defined $defaultvalue ) {
2526 $defaultvalue = q||;
2528 $defaultvalue =~ s/"/"/g;
2530 # search for itemcallnumber if applicable
2531 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2532 && C4::Context->preference('itemcallnumber') ) {
2533 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2534 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2536 my $temp = $itemrecord->field($CNtag);
2538 $defaultvalue = $temp->subfield($CNsubfield);
2542 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2544 && $defaultvalues->{'callnumber'} ) {
2547 $temp = $itemrecord->field($subfield);
2550 $defaultvalue = $defaultvalues->{'callnumber'} if $defaultvalues;
2553 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2555 && $defaultvalues->{'branchcode'} ) {
2558 $temp = $itemrecord->field($subfield);
2561 $defaultvalue = $defaultvalues->{branchcode} if $defaultvalues;
2564 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2566 && $defaultvalues->{'location'} ) {
2567 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2569 $defaultvalue = $defaultvalues->{location} if $defaultvalues;
2572 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2573 my @authorised_values;
2576 # builds list, depending on authorised value...
2578 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2579 if ( ( C4::Context->preference("IndependantBranches") )
2580 && ( C4::Context->userenv->{flags} % 2 != 1 ) ) {
2581 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2582 $sth->execute( C4::Context->userenv->{branch} );
2583 push @authorised_values, ""
2584 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2585 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2586 push @authorised_values, $branchcode;
2587 $authorised_lib{$branchcode} = $branchname;
2590 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2592 push @authorised_values, ""
2593 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2594 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2595 push @authorised_values, $branchcode;
2596 $authorised_lib{$branchcode} = $branchname;
2601 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2602 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2604 push @authorised_values, ""
2605 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2606 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2607 push @authorised_values, $itemtype;
2608 $authorised_lib{$itemtype} = $description;
2611 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2612 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2614 my $class_sources = GetClassSources();
2615 my $default_source = C4::Context->preference("DefaultClassificationSource");
2617 foreach my $class_source (sort keys %$class_sources) {
2618 next unless $class_sources->{$class_source}->{'used'} or
2619 ($class_source eq $default_source);
2620 push @authorised_values, $class_source;
2621 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2624 #---- "true" authorised value
2626 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
2627 push @authorised_values, ""
2628 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2629 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2630 push @authorised_values, $value;
2631 $authorised_lib{$value} = $lib;
2634 $subfield_data{marc_value} = CGI::scrolling_list(
2635 -name => 'field_value',
2636 -values => \@authorised_values,
2637 -default => "$defaultvalue",
2638 -labels => \%authorised_lib,
2643 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2645 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
2648 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2649 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2650 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
2651 my $index_subfield = int(rand(1000000));
2652 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
2653 $subfield_data{marc_value} = qq[<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255"
2654 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
2655 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
2656 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
2659 warn "Plugin Failed: $plugin";
2660 $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
2663 elsif ( $tag eq '' ) { # it's an hidden field
2664 $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" />);
2666 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2667 $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" />);
2669 elsif ( length($defaultvalue) > 100
2670 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2671 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2672 or (C4::Context->preference("marcflavour") eq "MARC21" and
2673 500 <= $tag && $tag < 600 )
2675 # oversize field (textarea)
2676 $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");
2678 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2680 push( @loop_data, \%subfield_data );
2685 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2686 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2689 'itemtagfield' => $itemtagfield,
2690 'itemtagsubfield' => $itemtagsubfield,
2691 'itemnumber' => $itemnumber,
2692 'iteminformation' => \@loop_data
2699 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2701 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2702 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2703 # =head2 ModZebrafiles
2705 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2709 # sub ModZebrafiles {
2711 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2715 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2716 # unless ( opendir( DIR, "$zebradir" ) ) {
2717 # warn "$zebradir not found";
2721 # my $filename = $zebradir . $biblionumber;
2724 # open( OUTPUT, ">", $filename . ".xml" );
2725 # print OUTPUT $record;
2732 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2734 $biblionumber is the biblionumber we want to index
2736 $op is specialUpdate or delete, and is used to know what we want to do
2738 $server is the server that we want to update
2740 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2741 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2744 $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.
2749 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2750 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2751 my $dbh = C4::Context->dbh;
2753 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2755 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2756 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2758 if ( C4::Context->preference("NoZebra") ) {
2760 # lock the nozebra table : we will read index lines, update them in Perl process
2761 # and write everything in 1 transaction.
2762 # lock the table to avoid someone else overwriting what we are doing
2763 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2764 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2765 if ( $op eq 'specialUpdate' ) {
2767 # OK, we have to add or update the record
2768 # 1st delete (virtually, in indexes), if record actually exists
2770 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2773 # ... add the record
2774 %result = _AddBiblioNoZebra( $biblionumber, $newRecord, $server, %result );
2777 # it's a deletion, delete the record...
2778 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2779 %result = _DelBiblioNoZebra( $biblionumber, $oldRecord, $server );
2782 # ok, now update the database...
2783 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2784 foreach my $key ( keys %result ) {
2785 foreach my $index ( keys %{ $result{$key} } ) {
2786 $sth->execute( $result{$key}->{$index}, $server, $key, $index );
2789 $dbh->do('UNLOCK TABLES');
2793 # we use zebra, just fill zebraqueue table
2795 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2797 AND biblio_auth_number = ?
2800 my $check_sth = $dbh->prepare_cached($check_sql);
2801 $check_sth->execute( $server, $biblionumber, $op );
2802 my ($count) = $check_sth->fetchrow_array;
2803 $check_sth->finish();
2804 if ( $count == 0 ) {
2805 my $sth = $dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2806 $sth->execute( $biblionumber, $server, $op );
2812 =head2 GetNoZebraIndexes
2814 %indexes = GetNoZebraIndexes;
2816 return the data from NoZebraIndexes syspref.
2820 sub GetNoZebraIndexes {
2821 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2823 INDEX: foreach my $line ( split /['"],[\n\r]*/, $no_zebra_indexes ) {
2824 $line =~ /(.*)=>(.*)/;
2825 my $index = $1; # initial ' or " is removed afterwards
2827 $index =~ s/'|"|\s//g;
2828 $fields =~ s/'|"|\s//g;
2829 $indexes{$index} = $fields;
2834 =head2 EmbedItemsInMarcBiblio
2836 EmbedItemsInMarcBiblio($marc, $biblionumber);
2838 Given a MARC::Record object containing a bib record,
2839 modify it to include the items attached to it as 9XX
2840 per the bib's MARC framework.
2844 sub EmbedItemsInMarcBiblio {
2845 my ($marc, $biblionumber) = @_;
2846 croak "No MARC record" unless $marc;
2848 my $frameworkcode = GetFrameworkCode($biblionumber);
2849 _strip_item_fields($marc, $frameworkcode);
2851 # ... and embed the current items
2852 my $dbh = C4::Context->dbh;
2853 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
2854 $sth->execute($biblionumber);
2856 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2857 while (my ($itemnumber) = $sth->fetchrow_array) {
2858 my $item_marc = C4::Items::GetMarcItem($biblionumber, $itemnumber);
2859 push @item_fields, $item_marc->field($itemtag);
2861 $marc->append_fields(@item_fields);
2864 =head1 INTERNAL FUNCTIONS
2866 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2868 function to delete a biblio in NoZebra indexes
2869 This function does NOT delete anything in database : it reads all the indexes entries
2870 that have to be deleted & delete them in the hash
2872 The SQL part is done either :
2873 - after the Add if we are modifying a biblio (delete + add again)
2874 - immediatly after this sub if we are doing a true deletion.
2876 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2880 sub _DelBiblioNoZebra {
2881 my ( $biblionumber, $record, $server ) = @_;
2884 my $dbh = C4::Context->dbh;
2889 if ( $server eq 'biblioserver' ) {
2890 %index = GetNoZebraIndexes;
2892 # get title of the record (to store the 10 first letters with the index)
2893 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
2894 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
2897 # for authorities, the "title" is the $a mainentry
2898 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
2899 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
2900 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
2901 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
2902 $index{'mainmainentry'} = $authref->{'auth_tag_to_report'} . 'a';
2903 $index{'mainentry'} = $authref->{'auth_tag_to_report'} . '*';
2904 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2909 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2910 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2912 # limit to 10 char, should be enough, and limit the DB size
2913 $title = substr( $title, 0, 10 );
2916 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2917 foreach my $field ( $record->fields() ) {
2919 #parse each subfield
2920 next if $field->tag < 10;
2921 foreach my $subfield ( $field->subfields() ) {
2922 my $tag = $field->tag();
2923 my $subfieldcode = $subfield->[0];
2926 # check each index to see if the subfield is stored somewhere
2927 # otherwise, store it in __RAW__ index
2928 foreach my $key ( keys %index ) {
2930 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2931 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
2933 my $line = lc $subfield->[1];
2935 # remove meaningless value in the field...
2936 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2938 # ... and split in words
2939 foreach ( split / /, $line ) {
2940 next unless $_; # skip empty values (multiple spaces)
2941 # if the entry is already here, do nothing, the biblionumber has already be removed
2942 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/ ) ) {
2944 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2945 $sth2->execute( $server, $key, $_ );
2946 my $existing_biblionumbers = $sth2->fetchrow;
2949 if ($existing_biblionumbers) {
2951 # warn " existing for $key $_: $existing_biblionumbers";
2952 $result{$key}->{$_} = $existing_biblionumbers;
2953 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2960 # the subfield is not indexed, store it in __RAW__ index anyway
2962 my $line = lc $subfield->[1];
2963 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2965 # ... and split in words
2966 foreach ( split / /, $line ) {
2967 next unless $_; # skip empty values (multiple spaces)
2968 # if the entry is already here, do nothing, the biblionumber has already be removed
2969 unless ( $result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/ ) {
2971 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2972 $sth2->execute( $server, '__RAW__', $_ );
2973 my $existing_biblionumbers = $sth2->fetchrow;
2976 if ($existing_biblionumbers) {
2977 $result{'__RAW__'}->{$_} = $existing_biblionumbers;
2978 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2988 =head2 _AddBiblioNoZebra
2990 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2992 function to add a biblio in NoZebra indexes
2996 sub _AddBiblioNoZebra {
2997 my ( $biblionumber, $record, $server, %result ) = @_;
2998 my $dbh = C4::Context->dbh;
3003 if ( $server eq 'biblioserver' ) {
3004 %index = GetNoZebraIndexes;
3006 # get title of the record (to store the 10 first letters with the index)
3007 my ( $titletag, $titlesubfield ) = GetMarcFromKohaField( 'biblio.title', '' ); # FIXME: should be GetFrameworkCode($biblionumber) ??
3008 $title = lc( $record->subfield( $titletag, $titlesubfield ) );
3011 # warn "server : $server";
3012 # for authorities, the "title" is the $a mainentry
3013 my ( $auth_type_tag, $auth_type_sf ) = C4::AuthoritiesMarc::get_auth_type_location();
3014 my $authref = C4::AuthoritiesMarc::GetAuthType( $record->subfield( $auth_type_tag, $auth_type_sf ) );
3015 warn "ERROR : authtype undefined for " . $record->as_formatted unless $authref;
3016 $title = $record->subfield( $authref->{auth_tag_to_report}, 'a' );
3017 $index{'mainmainentry'} = $authref->{auth_tag_to_report} . 'a';
3018 $index{'mainentry'} = $authref->{auth_tag_to_report} . '*';
3019 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
3022 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
3023 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
3025 # limit to 10 char, should be enough, and limit the DB size
3026 $title = substr( $title, 0, 10 );
3029 my $sth2 = $dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
3030 foreach my $field ( $record->fields() ) {
3032 #parse each subfield
3033 ###FIXME: impossible to index a 001-009 value with NoZebra
3034 next if $field->tag < 10;
3035 foreach my $subfield ( $field->subfields() ) {
3036 my $tag = $field->tag();
3037 my $subfieldcode = $subfield->[0];
3040 # warn "INDEXING :".$subfield->[1];
3041 # check each index to see if the subfield is stored somewhere
3042 # otherwise, store it in __RAW__ index
3043 foreach my $key ( keys %index ) {
3045 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
3046 if ( $index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/ ) {
3048 my $line = lc $subfield->[1];
3050 # remove meaningless value in the field...
3051 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
3053 # ... and split in words
3054 foreach ( split / /, $line ) {
3055 next unless $_; # skip empty values (multiple spaces)
3056 # if the entry is already here, improve weight
3058 # warn "managing $_";
3059 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
3060 my $weight = $1 + 1;
3061 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
3062 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3065 # get the value if it exist in the nozebra table, otherwise, create it
3066 $sth2->execute( $server, $key, $_ );
3067 my $existing_biblionumbers = $sth2->fetchrow;
3070 if ($existing_biblionumbers) {
3071 $result{$key}->{"$_"} = $existing_biblionumbers;
3072 my $weight = defined $1 ? $1 + 1 : 1;
3073 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
3074 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
3076 # create a new ligne for this entry
3079 # warn "INSERT : $server / $key / $_";
3080 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname=' . $dbh->quote($key) . ',value=' . $dbh->quote($_) );
3081 $result{$key}->{"$_"} .= "$biblionumber,$title-1;";
3088 # the subfield is not indexed, store it in __RAW__ index anyway
3090 my $line = lc $subfield->[1];
3091 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
3093 # ... and split in words
3094 foreach ( split / /, $line ) {
3095 next unless $_; # skip empty values (multiple spaces)
3096 # if the entry is already here, improve weight
3097 my $tmpstr = $result{'__RAW__'}->{"$_"} || "";
3098 if ( $tmpstr =~ /$biblionumber,\Q$title\E\-(\d+);/ ) {
3099 my $weight = $1 + 1;
3100 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
3101 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3104 # get the value if it exist in the nozebra table, otherwise, create it
3105 $sth2->execute( $server, '__RAW__', $_ );
3106 my $existing_biblionumbers = $sth2->fetchrow;
3109 if ($existing_biblionumbers) {
3110 $result{'__RAW__'}->{"$_"} = $existing_biblionumbers;
3111 my $weight = ( $1 ? $1 : 0 ) + 1;
3112 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
3113 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
3115 # create a new ligne for this entry
3117 $dbh->do( 'INSERT INTO nozebra SET server=' . $dbh->quote($server) . ', indexname="__RAW__",value=' . $dbh->quote($_) );
3118 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-1;";
3130 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
3132 Find the given $subfield in the given $tag in the given
3133 MARC::Record $record. If the subfield is found, returns
3134 the (indicators, value) pair; otherwise, (undef, undef) is
3138 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
3139 I suggest we export it from this module.
3144 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
3147 if ( $tagfield < 10 ) {
3148 if ( $record->field($tagfield) ) {
3149 push @result, $record->field($tagfield)->data();
3154 foreach my $field ( $record->field($tagfield) ) {
3155 my @subfields = $field->subfields();
3156 foreach my $subfield (@subfields) {
3157 if ( @$subfield[0] eq $insubfield ) {
3158 push @result, @$subfield[1];
3159 $indicator = $field->indicator(1) . $field->indicator(2);
3164 return ( $indicator, @result );
3167 =head2 _koha_marc_update_bib_ids
3170 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
3172 Internal function to add or update biblionumber and biblioitemnumber to
3177 sub _koha_marc_update_bib_ids {
3178 my ( $record, $frameworkcode, $biblionumber, $biblioitemnumber ) = @_;
3180 # we must add bibnum and bibitemnum in MARC::Record...
3181 # we build the new field with biblionumber and biblioitemnumber
3182 # we drop the original field
3183 # we add the new builded field.
3184 my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField( "biblio.biblionumber", $frameworkcode );
3185 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber", $frameworkcode );
3187 if ( $biblio_tag != $biblioitem_tag ) {
3189 # biblionumber & biblioitemnumber are in different fields
3191 # deal with biblionumber
3192 my ( $new_field, $old_field );
3193 if ( $biblio_tag < 10 ) {
3194 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
3196 $new_field = MARC::Field->new( $biblio_tag, '', '', "$biblio_subfield" => $biblionumber );
3199 # drop old field and create new one...
3200 $old_field = $record->field($biblio_tag);
3201 $record->delete_field($old_field) if $old_field;
3202 $record->insert_fields_ordered($new_field);
3204 # deal with biblioitemnumber
3205 if ( $biblioitem_tag < 10 ) {
3206 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
3208 $new_field = MARC::Field->new( $biblioitem_tag, '', '', "$biblioitem_subfield" => $biblioitemnumber, );
3211 # drop old field and create new one...
3212 $old_field = $record->field($biblioitem_tag);
3213 $record->delete_field($old_field) if $old_field;
3214 $record->insert_fields_ordered($new_field);
3218 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
3219 my $new_field = MARC::Field->new(
3220 $biblio_tag, '', '',
3221 "$biblio_subfield" => $biblionumber,
3222 "$biblioitem_subfield" => $biblioitemnumber
3225 # drop old field and create new one...
3226 my $old_field = $record->field($biblio_tag);
3227 $record->delete_field($old_field) if $old_field;
3228 $record->insert_fields_ordered($new_field);
3232 =head2 _koha_marc_update_biblioitem_cn_sort
3234 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
3236 Given a MARC bib record and the biblioitem hash, update the
3237 subfield that contains a copy of the value of biblioitems.cn_sort.
3241 sub _koha_marc_update_biblioitem_cn_sort {
3243 my $biblioitem = shift;
3244 my $frameworkcode = shift;
3246 my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.cn_sort", $frameworkcode );
3247 return unless $biblioitem_tag;
3249 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3251 if ( my $field = $marc->field($biblioitem_tag) ) {
3252 $field->delete_subfield( code => $biblioitem_subfield );
3253 if ( $cn_sort ne '' ) {
3254 $field->add_subfields( $biblioitem_subfield => $cn_sort );
3258 # if we get here, no biblioitem tag is present in the MARC record, so
3259 # we'll create it if $cn_sort is not empty -- this would be
3260 # an odd combination of events, however
3262 $marc->insert_grouped_field( MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) );
3267 =head2 _koha_add_biblio
3269 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
3271 Internal function to add a biblio ($biblio is a hash with the values)
3275 sub _koha_add_biblio {
3276 my ( $dbh, $biblio, $frameworkcode ) = @_;
3280 # set the series flag
3281 unless (defined $biblio->{'serial'}){
3282 $biblio->{'serial'} = 0;
3283 if ( $biblio->{'seriestitle'} ) { $biblio->{'serial'} = 1 }
3286 my $query = "INSERT INTO biblio
3287 SET frameworkcode = ?,
3298 my $sth = $dbh->prepare($query);
3300 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
3301 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}
3304 my $biblionumber = $dbh->{'mysql_insertid'};
3305 if ( $dbh->errstr ) {
3306 $error .= "ERROR in _koha_add_biblio $query" . $dbh->errstr;
3312 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3313 return ( $biblionumber, $error );
3316 =head2 _koha_modify_biblio
3318 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3320 Internal function for updating the biblio table
3324 sub _koha_modify_biblio {
3325 my ( $dbh, $biblio, $frameworkcode ) = @_;
3330 SET frameworkcode = ?,
3339 WHERE biblionumber = ?
3342 my $sth = $dbh->prepare($query);
3345 $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'unititle'}, $biblio->{'notes'},
3346 $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'}, $biblio->{'abstract'}, $biblio->{'biblionumber'}
3347 ) if $biblio->{'biblionumber'};
3349 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3350 $error .= "ERROR in _koha_modify_biblio $query" . $dbh->errstr;
3353 return ( $biblio->{'biblionumber'}, $error );
3356 =head2 _koha_modify_biblioitem_nonmarc
3358 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3360 Updates biblioitems row except for marc and marcxml, which should be changed
3365 sub _koha_modify_biblioitem_nonmarc {
3366 my ( $dbh, $biblioitem ) = @_;
3369 # re-calculate the cn_sort, it may have changed
3370 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3372 my $query = "UPDATE biblioitems
3373 SET biblionumber = ?,
3379 publicationyear = ?,
3383 collectiontitle = ?,
3385 collectionvolume= ?,
3386 editionstatement= ?,
3387 editionresponsibility = ?,
3401 where biblioitemnumber = ?
3403 my $sth = $dbh->prepare($query);
3405 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3406 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3407 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3408 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3409 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3410 $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'},
3411 $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'},
3412 $biblioitem->{'biblioitemnumber'}
3414 if ( $dbh->errstr ) {
3415 $error .= "ERROR in _koha_modify_biblioitem_nonmarc $query" . $dbh->errstr;
3418 return ( $biblioitem->{'biblioitemnumber'}, $error );
3421 =head2 _koha_add_biblioitem
3423 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3425 Internal function to add a biblioitem
3429 sub _koha_add_biblioitem {
3430 my ( $dbh, $biblioitem ) = @_;
3433 my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3434 my $query = "INSERT INTO biblioitems SET
3441 publicationyear = ?,
3445 collectiontitle = ?,
3447 collectionvolume= ?,
3448 editionstatement= ?,
3449 editionresponsibility = ?,
3465 my $sth = $dbh->prepare($query);
3467 $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'},
3468 $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'},
3469 $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'},
3470 $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'},
3471 $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'},
3472 $biblioitem->{'lccn'}, $biblioitem->{'marc'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'},
3473 $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort,
3474 $biblioitem->{'totalissues'}
3476 my $bibitemnum = $dbh->{'mysql_insertid'};
3478 if ( $dbh->errstr ) {
3479 $error .= "ERROR in _koha_add_biblioitem $query" . $dbh->errstr;
3483 return ( $bibitemnum, $error );
3486 =head2 _koha_delete_biblio
3488 $error = _koha_delete_biblio($dbh,$biblionumber);
3490 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3492 C<$dbh> - the database handle
3494 C<$biblionumber> - the biblionumber of the biblio to be deleted
3498 # FIXME: add error handling
3500 sub _koha_delete_biblio {
3501 my ( $dbh, $biblionumber ) = @_;
3503 # get all the data for this biblio
3504 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3505 $sth->execute($biblionumber);
3507 if ( my $data = $sth->fetchrow_hashref ) {
3509 # save the record in deletedbiblio
3510 # find the fields to save
3511 my $query = "INSERT INTO deletedbiblio SET ";
3513 foreach my $temp ( keys %$data ) {
3514 $query .= "$temp = ?,";
3515 push( @bind, $data->{$temp} );
3518 # replace the last , by ",?)"
3520 my $bkup_sth = $dbh->prepare($query);
3521 $bkup_sth->execute(@bind);
3525 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3526 $del_sth->execute($biblionumber);
3533 =head2 _koha_delete_biblioitems
3535 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3537 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3539 C<$dbh> - the database handle
3540 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3544 # FIXME: add error handling
3546 sub _koha_delete_biblioitems {
3547 my ( $dbh, $biblioitemnumber ) = @_;
3549 # get all the data for this biblioitem
3550 my $sth = $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3551 $sth->execute($biblioitemnumber);
3553 if ( my $data = $sth->fetchrow_hashref ) {
3555 # save the record in deletedbiblioitems
3556 # find the fields to save
3557 my $query = "INSERT INTO deletedbiblioitems SET ";
3559 foreach my $temp ( keys %$data ) {
3560 $query .= "$temp = ?,";
3561 push( @bind, $data->{$temp} );
3564 # replace the last , by ",?)"
3566 my $bkup_sth = $dbh->prepare($query);
3567 $bkup_sth->execute(@bind);
3570 # delete the biblioitem
3571 my $del_sth = $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3572 $del_sth->execute($biblioitemnumber);
3579 =head1 UNEXPORTED FUNCTIONS
3581 =head2 ModBiblioMarc
3583 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3585 Add MARC data for a biblio to koha
3587 Function exported, but should NOT be used, unless you really know what you're doing
3593 # pass the MARC::Record to this function, and it will create the records in the marc field
3594 my ( $record, $biblionumber, $frameworkcode ) = @_;
3595 my $dbh = C4::Context->dbh;
3596 my @fields = $record->fields();
3597 if ( !$frameworkcode ) {
3598 $frameworkcode = "";
3600 my $sth = $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3601 $sth->execute( $frameworkcode, $biblionumber );
3603 my $encoding = C4::Context->preference("marcflavour");
3605 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3606 if ( $encoding eq "UNIMARC" ) {
3607 my $string = $record->subfield( 100, "a" );
3608 if ( ($string) && ( length( $record->subfield( 100, "a" ) ) == 36 ) ) {
3609 my $f100 = $record->field(100);
3610 $record->delete_field($f100);
3612 $string = POSIX::strftime( "%Y%m%d", localtime );
3614 $string = sprintf( "%-*s", 35, $string );
3616 substr( $string, 22, 6, "frey50" );
3617 unless ( $record->subfield( 100, "a" ) ) {
3618 $record->insert_fields_ordered( MARC::Field->new( 100, "", "", "a" => $string ) );
3622 #enhancement 5374: update transaction date (005) for marc21/unimarc
3623 if($encoding =~ /MARC21|UNIMARC/) {
3624 my @a= (localtime) [5,4,3,2,1,0]; $a[0]+=1900; $a[1]++;
3625 # YY MM DD HH MM SS (update year and month)
3626 my $f005= $record->field('005');
3627 $f005->update(sprintf("%4d%02d%02d%02d%02d%04.1f",@a)) if $f005;
3631 if ( C4::Context->preference("NoZebra") ) {
3633 # only NoZebra indexing needs to have
3634 # the previous version of the record
3635 $oldRecord = GetMarcBiblio($biblionumber);
3637 $sth = $dbh->prepare("UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3638 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding), $biblionumber );
3640 ModZebra( $biblionumber, "specialUpdate", "biblioserver", $oldRecord, $record );
3641 return $biblionumber;
3644 =head2 z3950_extended_services
3646 z3950_extended_services($serviceType,$serviceOptions,$record);
3648 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.
3650 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3652 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3654 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3658 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3659 syntax => the record syntax (transfer syntax)
3660 databaseName = Database from connection object
3662 To set serviceOptions, call set_service_options($serviceType)
3664 C<$record> the record, if one is needed for the service type
3666 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3670 sub z3950_extended_services {
3671 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3673 # get our connection object
3674 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3676 # create a new package object
3677 my $Zpackage = $Zconn->package();
3680 $Zpackage->option( action => $action );
3682 if ( $serviceOptions->{'databaseName'} ) {
3683 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3685 if ( $serviceOptions->{'recordIdNumber'} ) {
3686 $Zpackage->option( recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3688 if ( $serviceOptions->{'recordIdOpaque'} ) {
3689 $Zpackage->option( recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3692 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3693 #if ($serviceType eq 'itemorder') {
3694 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3695 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3696 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3697 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3700 if ( $serviceOptions->{record} ) {
3701 $Zpackage->option( record => $serviceOptions->{record} );
3703 # can be xml or marc
3704 if ( $serviceOptions->{'syntax'} ) {
3705 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3709 # send the request, handle any exception encountered
3710 eval { $Zpackage->send($serviceType) };
3711 if ( $@ && $@->isa("ZOOM::Exception") ) {
3712 return "error: " . $@->code() . " " . $@->message() . "\n";
3715 # free up package resources
3716 $Zpackage->destroy();
3719 =head2 set_service_options
3721 my $serviceOptions = set_service_options($serviceType);
3723 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3725 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3729 sub set_service_options {
3730 my ($serviceType) = @_;
3733 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3734 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3736 if ( $serviceType eq 'commit' ) {
3740 if ( $serviceType eq 'create' ) {
3744 if ( $serviceType eq 'drop' ) {
3745 die "ERROR: 'drop' not currently supported (by Zebra)";
3747 return $serviceOptions;
3750 =head2 get_biblio_authorised_values
3752 find the types and values for all authorised values assigned to this biblio.
3756 MARC::Record of the bib
3758 returns: a hashref mapping the authorised value to the value set for this biblionumber
3760 $authorised_values = {
3761 'Scent' => 'flowery',
3762 'Audience' => 'Young Adult',
3763 'itemtypes' => 'SER',
3766 Notes: forlibrarian should probably be passed in, and called something different.
3770 sub get_biblio_authorised_values {
3771 my $biblionumber = shift;
3774 my $forlibrarian = 1; # are we in staff or opac?
3775 my $frameworkcode = GetFrameworkCode($biblionumber);
3777 my $authorised_values;
3779 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3780 or return $authorised_values;
3782 # assume that these entries in the authorised_value table are bibliolevel.
3783 # ones that start with 'item%' are item level.
3784 my $query = q(SELECT distinct authorised_value, kohafield
3785 FROM marc_subfield_structure
3786 WHERE authorised_value !=''
3787 AND (kohafield like 'biblio%'
3788 OR kohafield like '') );
3789 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3791 foreach my $tag ( keys(%$tagslib) ) {
3792 foreach my $subfield ( keys( %{ $tagslib->{$tag} } ) ) {
3794 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3795 if ( 'HASH' eq ref $tagslib->{$tag}{$subfield} ) {
3796 if ( defined $tagslib->{$tag}{$subfield}{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } ) {
3797 if ( defined $record->field($tag) ) {
3798 my $this_subfield_value = $record->field($tag)->subfield($subfield);
3799 if ( defined $this_subfield_value ) {
3800 $authorised_values->{ $tagslib->{$tag}{$subfield}{'authorised_value'} } = $this_subfield_value;
3808 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3809 return $authorised_values;
3812 =head2 CountBiblioInOrders
3815 $count = &CountBiblioInOrders( $biblionumber);
3819 This function return count of biblios in orders with $biblionumber
3823 sub CountBiblioInOrders {
3824 my ($biblionumber) = @_;
3825 my $dbh = C4::Context->dbh;
3826 my $query = "SELECT count(*)
3828 WHERE biblionumber=? AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')";
3829 my $sth = $dbh->prepare($query);
3830 $sth->execute($biblionumber);
3831 my $count = $sth->fetchrow;
3835 =head2 GetSubscriptionsId
3838 $subscriptions = &GetSubscriptionsId($biblionumber);
3842 This function return an array of subscriptionid with $biblionumber
3846 sub GetSubscriptionsId {
3847 my ($biblionumber) = @_;
3848 my $dbh = C4::Context->dbh;
3849 my $query = "SELECT subscriptionid
3851 WHERE biblionumber=?";
3852 my $sth = $dbh->prepare($query);
3853 $sth->execute($biblionumber);
3854 my @subscriptions = $sth->fetchrow_array;
3855 return (@subscriptions);
3861 $holds = &GetHolds($biblionumber);
3865 This function return the count of holds with $biblionumber
3870 my ($biblionumber) = @_;
3871 my $dbh = C4::Context->dbh;
3872 my $query = "SELECT count(*)
3874 WHERE biblionumber=?";
3875 my $sth = $dbh->prepare($query);
3876 $sth->execute($biblionumber);
3877 my $holds = $sth->fetchrow;
3888 Koha Development Team <http://koha-community.org/>
3890 Paul POULAIN paul.poulain@free.fr
3892 Joshua Ferraro jmf@liblime.com