3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
24 use MARC::File::USMARC;
25 # Force MARC::File::XML to use LibXML SAX Parser
26 #$XML::SAX::ParserPackage = "XML::LibXML::SAX";
29 use POSIX qw(strftime);
32 use C4::Dates qw/format_date/;
33 use C4::Log; # logaction
39 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
45 @ISA = qw( Exporter );
63 &GetBiblioItemByBiblioNumber
64 &GetBiblioFromItemNumber
83 &GetAuthorisedValueDesc
87 &GetPublisherNameFromIsbn
104 # To link headings in a bib record
105 # to authority records.
107 &LinkBibHeadingsToAuthorities
111 # those functions are exported but should not be used
112 # they are usefull is few circumstances, so are exported.
113 # but don't use them unless you're a core developer ;-)
120 &TransformHtmlToMarc2
123 &PrepareItemrecordDisplay
130 C4::Biblio - cataloging management functions
134 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:
138 =item 1. in the biblio,biblioitems,items, etc tables, which are limited to a one-to-one mapping to underlying MARC data
140 =item 2. as raw MARC in the Zebra index and storage engine
142 =item 3. as raw MARC the biblioitems.marc and biblioitems.marcxml
146 In the 3.0 version of Koha, the authoritative record-level information is in biblioitems.marcxml
148 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.
152 =item 1. Compared with MySQL, Zebra is slow to update an index for small data changes -- especially for proc-intensive operations like circulation
154 =item 2. Zebra's index has been known to crash and a backup of the data is necessary to rebuild it in such cases
158 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:
162 =item 1. Add*/Mod*/Del*/ - high-level external functions suitable for being called from external scripts to manage the collection
164 =item 2. _koha_* - low-level internal functions for managing the koha tables
166 =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.
168 =item 4. Zebra functions used to update the Zebra index
170 =item 5. internal helper functions such as char_decode, checkitems, etc. Some of these probably belong in Koha.pm
174 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 :
178 =item 1. save datas in biblio and biblioitems table, that gives us a biblionumber and a biblioitemnumber
180 =item 2. add the biblionumber and biblioitemnumber into the MARC records
182 =item 3. save the marc record
186 When dealing with items, we must :
190 =item 1. save the item in items table, that gives us an itemnumber
192 =item 2. add the itemnumber to the item MARC field
194 =item 3. overwrite the MARC record (with the added item) into biblioitems.marc(xml)
196 When modifying a biblio or an item, the behaviour is quite similar.
200 =head1 EXPORTED FUNCTIONS
206 ($biblionumber,$biblioitemnumber) = AddBiblio($record,$frameworkcode);
210 Exported function (core API) for adding a new biblio to koha.
212 The first argument is a C<MARC::Record> object containing the
213 bib to add, while the second argument is the desired MARC
216 This function also accepts a third, optional argument: a hashref
217 to additional options. The only defined option is C<defer_marc_save>,
218 which if present and mapped to a true value, causes C<AddBiblio>
219 to omit the call to save the MARC in C<bibilioitems.marc>
220 and C<biblioitems.marcxml> This option is provided B<only>
221 for the use of scripts such as C<bulkmarcimport.pl> that may need
222 to do some manipulation of the MARC record for item parsing before
223 saving it and which cannot afford the performance hit of saving
224 the MARC record twice. Consequently, do not use that option
225 unless you can guarantee that C<ModBiblioMarc> will be called.
231 my $frameworkcode = shift;
232 my $options = @_ ? shift : undef;
233 my $defer_marc_save = 0;
234 if (defined $options and exists $options->{'defer_marc_save'} and $options->{'defer_marc_save'}) {
235 $defer_marc_save = 1;
238 my ($biblionumber,$biblioitemnumber,$error);
239 my $dbh = C4::Context->dbh;
240 # transform the data into koha-table style data
241 my $olddata = TransformMarcToKoha( $dbh, $record, $frameworkcode );
242 ($biblionumber,$error) = _koha_add_biblio( $dbh, $olddata, $frameworkcode );
243 $olddata->{'biblionumber'} = $biblionumber;
244 ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $olddata );
246 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
248 # update MARC subfield that stores biblioitems.cn_sort
249 _koha_marc_update_biblioitem_cn_sort($record, $olddata, $frameworkcode);
252 ModBiblioMarc( $record, $biblionumber, $frameworkcode ) unless $defer_marc_save;
254 logaction("CATALOGUING", "ADD", $biblionumber, "biblio") if C4::Context->preference("CataloguingLog");
255 return ( $biblionumber, $biblioitemnumber );
262 ModBiblio( $record,$biblionumber,$frameworkcode);
266 Replace an existing bib record identified by C<$biblionumber>
267 with one supplied by the MARC::Record object C<$record>. The embedded
268 item, biblioitem, and biblionumber fields from the previous
269 version of the bib record replace any such fields of those tags that
270 are present in C<$record>. Consequently, ModBiblio() is not
271 to be used to try to modify item records.
273 C<$frameworkcode> specifies the MARC framework to use
274 when storing the modified bib record; among other things,
275 this controls how MARC fields get mapped to display columns
276 in the C<biblio> and C<biblioitems> tables, as well as
277 which fields are used to store embedded item, biblioitem,
278 and biblionumber data for indexing.
283 my ( $record, $biblionumber, $frameworkcode ) = @_;
284 if (C4::Context->preference("CataloguingLog")) {
285 my $newrecord = GetMarcBiblio($biblionumber);
286 logaction("CATALOGUING", "MODIFY", $biblionumber, "BEFORE=>".$newrecord->as_formatted);
289 my $dbh = C4::Context->dbh;
291 $frameworkcode = "" unless $frameworkcode;
293 # get the items before and append them to the biblio before updating the record, atm we just have the biblio
294 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
295 my $oldRecord = GetMarcBiblio( $biblionumber );
297 # delete any item fields from incoming record to avoid
298 # duplication or incorrect data - use AddItem() or ModItem()
300 foreach my $field ($record->field($itemtag)) {
301 $record->delete_field($field);
304 # once all the items fields are removed, copy the old ones, in order to keep synchronize
305 $record->append_fields($oldRecord->field( $itemtag ));
307 # update biblionumber and biblioitemnumber in MARC
308 # FIXME - this is assuming a 1 to 1 relationship between
309 # biblios and biblioitems
310 my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?");
311 $sth->execute($biblionumber);
312 my ($biblioitemnumber) = $sth->fetchrow;
314 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
316 # load the koha-table data object
317 my $oldbiblio = TransformMarcToKoha( $dbh, $record, $frameworkcode );
319 # update MARC subfield that stores biblioitems.cn_sort
320 _koha_marc_update_biblioitem_cn_sort($record, $oldbiblio, $frameworkcode);
322 # update the MARC record (that now contains biblio and items) with the new record data
323 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
325 # modify the other koha tables
326 _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode );
327 _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio );
331 =head2 ModBiblioframework
333 ModBiblioframework($biblionumber,$frameworkcode);
334 Exported function to modify a biblio framework
338 sub ModBiblioframework {
339 my ( $biblionumber, $frameworkcode ) = @_;
340 my $dbh = C4::Context->dbh;
341 my $sth = $dbh->prepare(
342 "UPDATE biblio SET frameworkcode=? WHERE biblionumber=?"
344 $sth->execute($frameworkcode, $biblionumber);
352 my $error = &DelBiblio($dbh,$biblionumber);
353 Exported function (core API) for deleting a biblio in koha.
354 Deletes biblio record from Zebra and Koha tables (biblio,biblioitems,items)
355 Also backs it up to deleted* tables
356 Checks to make sure there are not issues on any of the items
358 C<$error> : undef unless an error occurs
365 my ( $biblionumber ) = @_;
366 my $dbh = C4::Context->dbh;
367 my $error; # for error handling
369 # First make sure this biblio has no items attached
370 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?");
371 $sth->execute($biblionumber);
372 if (my $itemnumber = $sth->fetchrow){
373 # Fix this to use a status the template can understand
374 $error .= "This Biblio has items attached, please delete them first before deleting this biblio ";
377 return $error if $error;
379 # We delete attached subscriptions
380 my $subscriptions = &C4::Serials::GetFullSubscriptionsFromBiblionumber($biblionumber);
381 foreach my $subscription (@$subscriptions){
382 &C4::Serials::DelSubscription($subscription->{subscriptionid});
385 # Delete in Zebra. Be careful NOT to move this line after _koha_delete_biblio
386 # for at least 2 reasons :
387 # - we need to read the biblio if NoZebra is set (to remove it from the indexes
388 # - if something goes wrong, the biblio may be deleted from Koha but not from zebra
389 # 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)
391 if (C4::Context->preference("NoZebra")) {
392 # only NoZebra indexing needs to have
393 # the previous version of the record
394 $oldRecord = GetMarcBiblio($biblionumber);
396 ModZebra($biblionumber, "recordDelete", "biblioserver", $oldRecord, undef);
398 # delete biblioitems and items from Koha tables and save in deletedbiblioitems,deleteditems
401 "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
402 $sth->execute($biblionumber);
403 while ( my $biblioitemnumber = $sth->fetchrow ) {
405 # delete this biblioitem
406 $error = _koha_delete_biblioitems( $dbh, $biblioitemnumber );
407 return $error if $error;
410 # delete biblio from Koha tables and save in deletedbiblio
411 # must do this *after* _koha_delete_biblioitems, otherwise
412 # delete cascade will prevent deletedbiblioitems rows
413 # from being generated by _koha_delete_biblioitems
414 $error = _koha_delete_biblio( $dbh, $biblionumber );
416 logaction("CATALOGUING", "DELETE", $biblionumber, "") if C4::Context->preference("CataloguingLog");
421 =head2 LinkBibHeadingsToAuthorities
425 my $headings_linked = LinkBibHeadingsToAuthorities($marc);
429 Links bib headings to authority records by checking
430 each authority-controlled field in the C<MARC::Record>
431 object C<$marc>, looking for a matching authority record,
432 and setting the linking subfield $9 to the ID of that
435 If no matching authority exists, or if multiple
436 authorities match, no $9 will be added, and any
437 existing one inthe field will be deleted.
439 Returns the number of heading links changed in the
444 sub LinkBibHeadingsToAuthorities {
447 my $num_headings_changed = 0;
448 foreach my $field ($bib->fields()) {
449 my $heading = C4::Heading->new_from_bib_field($field);
450 next unless defined $heading;
453 my $current_link = $field->subfield('9');
455 # look for matching authorities
456 my $authorities = $heading->authorities();
458 # want only one exact match
459 if ($#{ $authorities } == 0) {
460 my $authority = MARC::Record->new_from_usmarc($authorities->[0]);
461 my $authid = $authority->field('001')->data();
462 next if defined $current_link and $current_link eq $authid;
464 $field->delete_subfield(code => '9') if defined $current_link;
465 $field->add_subfields('9', $authid);
466 $num_headings_changed++;
468 if (defined $current_link) {
469 $field->delete_subfield(code => '9');
470 $num_headings_changed++;
475 return $num_headings_changed;
478 =head2 GetRecordValue
482 my $values = GetRecordValue($field, $record, $frameworkcode);
486 Get MARC fields from a keyword defined in fieldmapping table.
491 my ($field, $record, $frameworkcode) = @_;
492 my $dbh = C4::Context->dbh;
494 my $sth = $dbh->prepare('SELECT fieldcode, subfieldcode FROM fieldmapping WHERE frameworkcode = ? AND field = ?');
495 $sth->execute($frameworkcode, $field);
499 while(my $row = $sth->fetchrow_hashref){
500 foreach my $field ($record->field($row->{fieldcode})){
501 if( ($row->{subfieldcode} ne "" && $field->subfield($row->{subfieldcode}))){
502 foreach my $subfield ($field->subfield($row->{subfieldcode})){
503 push @result, { 'subfield' => $subfield };
506 }elsif($row->{subfieldcode} eq "") {
507 push @result, {'subfield' => $field->as_string()};
515 =head2 SetFieldMapping
519 SetFieldMapping($framework, $field, $fieldcode, $subfieldcode);
523 Set a Field to MARC mapping value, if it already exists we don't add a new one.
527 sub SetFieldMapping {
528 my ($framework, $field, $fieldcode, $subfieldcode) = @_;
529 my $dbh = C4::Context->dbh;
531 my $sth = $dbh->prepare('SELECT * FROM fieldmapping WHERE fieldcode = ? AND subfieldcode = ? AND frameworkcode = ? AND field = ?');
532 $sth->execute($fieldcode, $subfieldcode, $framework, $field);
533 if(not $sth->fetchrow_hashref){
535 $sth = $dbh->prepare('INSERT INTO fieldmapping (fieldcode, subfieldcode, frameworkcode, field) VALUES(?,?,?,?)');
537 $sth->execute($fieldcode, $subfieldcode, $framework, $field);
541 =head2 DeleteFieldMapping
545 DeleteFieldMapping($id);
549 Delete a field mapping from an $id.
553 sub DeleteFieldMapping{
555 my $dbh = C4::Context->dbh;
557 my $sth = $dbh->prepare('DELETE FROM fieldmapping WHERE id = ?');
561 =head2 GetFieldMapping
565 GetFieldMapping($frameworkcode);
569 Get all field mappings for a specified frameworkcode
573 sub GetFieldMapping {
574 my ($framework) = @_;
575 my $dbh = C4::Context->dbh;
577 my $sth = $dbh->prepare('SELECT * FROM fieldmapping where frameworkcode = ?');
578 $sth->execute($framework);
581 while(my $row = $sth->fetchrow_hashref){
591 $data = &GetBiblioData($biblionumber);
592 Returns information about the book with the given biblionumber.
593 C<&GetBiblioData> returns a reference-to-hash. The keys are the fields in
594 the C<biblio> and C<biblioitems> tables in the
596 In addition, C<$data-E<gt>{subject}> is the list of the book's
597 subjects, separated by C<" , "> (space, comma, space).
598 If there are multiple biblioitems with the given biblionumber, only
599 the first one is considered.
607 my $dbh = C4::Context->dbh;
609 # my $query = C4::Context->preference('item-level_itypes') ?
610 # " SELECT * , biblioitems.notes AS bnotes, biblio.notes
612 # LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
613 # WHERE biblio.biblionumber = ?
614 # AND biblioitems.biblionumber = biblio.biblionumber
617 my $query = " SELECT * , biblioitems.notes AS bnotes, itemtypes.notforloan as bi_notforloan, biblio.notes
619 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
620 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
621 WHERE biblio.biblionumber = ?
622 AND biblioitems.biblionumber = biblio.biblionumber ";
624 my $sth = $dbh->prepare($query);
625 $sth->execute($bibnum);
627 $data = $sth->fetchrow_hashref;
631 } # sub GetBiblioData
633 =head2 &GetBiblioItemData
637 $itemdata = &GetBiblioItemData($biblioitemnumber);
639 Looks up the biblioitem with the given biblioitemnumber. Returns a
640 reference-to-hash. The keys are the fields from the C<biblio>,
641 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
642 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
649 sub GetBiblioItemData {
650 my ($biblioitemnumber) = @_;
651 my $dbh = C4::Context->dbh;
652 my $query = "SELECT *,biblioitems.notes AS bnotes
653 FROM biblio LEFT JOIN biblioitems on biblio.biblionumber=biblioitems.biblionumber ";
654 unless(C4::Context->preference('item-level_itypes')) {
655 $query .= "LEFT JOIN itemtypes on biblioitems.itemtype=itemtypes.itemtype ";
657 $query .= " WHERE biblioitemnumber = ? ";
658 my $sth = $dbh->prepare($query);
660 $sth->execute($biblioitemnumber);
661 $data = $sth->fetchrow_hashref;
664 } # sub &GetBiblioItemData
666 =head2 GetBiblioItemByBiblioNumber
670 NOTE : This function has been copy/paste from C4/Biblio.pm from head before zebra integration.
676 sub GetBiblioItemByBiblioNumber {
677 my ($biblionumber) = @_;
678 my $dbh = C4::Context->dbh;
679 my $sth = $dbh->prepare("Select * FROM biblioitems WHERE biblionumber = ?");
683 $sth->execute($biblionumber);
685 while ( my $data = $sth->fetchrow_hashref ) {
686 push @results, $data;
693 =head2 GetBiblioFromItemNumber
697 $item = &GetBiblioFromItemNumber($itemnumber,$barcode);
699 Looks up the item with the given itemnumber. if undef, try the barcode.
701 C<&itemnodata> returns a reference-to-hash whose keys are the fields
702 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
710 sub GetBiblioFromItemNumber {
711 my ( $itemnumber, $barcode ) = @_;
712 my $dbh = C4::Context->dbh;
715 $sth=$dbh->prepare( "SELECT * FROM items
716 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
717 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
718 WHERE items.itemnumber = ?") ;
719 $sth->execute($itemnumber);
721 $sth=$dbh->prepare( "SELECT * FROM items
722 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
723 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
724 WHERE items.barcode = ?") ;
725 $sth->execute($barcode);
727 my $data = $sth->fetchrow_hashref;
736 $isbd = &GetISBDView($biblionumber);
738 Return the ISBD view which can be included in opac and intranet
745 my $biblionumber = shift;
746 my $record = GetMarcBiblio($biblionumber);
747 my $itemtype = &GetFrameworkCode($biblionumber);
748 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$itemtype);
749 my $tagslib = &GetMarcStructure( 1, $itemtype );
751 my $ISBD = C4::Context->preference('ISBD');
756 foreach my $isbdfield ( split (/#/, $bloc) ) {
758 # $isbdfield= /(.?.?.?)/;
759 $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/;
760 my $fieldvalue = $1 || 0;
761 my $subfvalue = $2 || "";
763 my $analysestring = $4;
766 # warn "==> $1 / $2 / $3 / $4";
767 # my $fieldvalue=substr($isbdfield,0,3);
768 if ( $fieldvalue > 0 ) {
769 my $hasputtextbefore = 0;
770 my @fieldslist = $record->field($fieldvalue);
771 @fieldslist = sort {$a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf)} @fieldslist if ($fieldvalue eq $holdingbrtagf);
773 # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
774 # warn "FV : $fieldvalue";
775 if ($subfvalue ne ""){
776 foreach my $field ( @fieldslist ) {
777 foreach my $subfield ($field->subfield($subfvalue)){
778 my $calculated = $analysestring;
779 my $tag = $field->tag();
784 GetAuthorisedValueDesc( $tag, $subfvalue,
785 $subfield, '', $tagslib );
786 my $tagsubf = $tag . $subfvalue;
788 s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
789 $calculated =~s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g;
791 # field builded, store the result
792 if ( $calculated && !$hasputtextbefore )
793 { # put textbefore if not done
794 $blocres .= $textbefore;
795 $hasputtextbefore = 1;
798 # remove punctuation at start
799 $calculated =~ s/^( |;|:|\.|-)*//g;
800 $blocres .= $calculated;
805 $blocres .= $textafter if $hasputtextbefore;
807 foreach my $field ( @fieldslist ) {
808 my $calculated = $analysestring;
809 my $tag = $field->tag();
813 my @subf = $field->subfields;
814 for my $i ( 0 .. $#subf ) {
815 my $valuecode = $subf[$i][1];
816 my $subfieldcode = $subf[$i][0];
818 GetAuthorisedValueDesc( $tag, $subf[$i][0],
819 $subf[$i][1], '', $tagslib );
820 my $tagsubf = $tag . $subfieldcode;
822 $calculated =~ s/ # replace all {{}} codes by the value code.
823 \{\{$tagsubf\}\} # catch the {{actualcode}}
825 $valuecode # replace by the value code
829 s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
830 $calculated =~s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g;
833 # field builded, store the result
834 if ( $calculated && !$hasputtextbefore )
835 { # put textbefore if not done
836 $blocres .= $textbefore;
837 $hasputtextbefore = 1;
840 # remove punctuation at start
841 $calculated =~ s/^( |;|:|\.|-)*//g;
842 $blocres .= $calculated;
845 $blocres .= $textafter if $hasputtextbefore;
849 $blocres .= $isbdfield;
854 $res =~ s/\{(.*?)\}//g;
856 $res =~ s/\n/<br\/>/g;
868 ( $count, @results ) = &GetBiblio($biblionumber);
875 my ($biblionumber) = @_;
876 my $dbh = C4::Context->dbh;
877 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber = ?");
880 $sth->execute($biblionumber);
881 while ( my $data = $sth->fetchrow_hashref ) {
882 $results[$count] = $data;
886 return ( $count, @results );
889 =head2 GetBiblioItemInfosOf
893 GetBiblioItemInfosOf(@biblioitemnumbers);
899 sub GetBiblioItemInfosOf {
900 my @biblioitemnumbers = @_;
903 SELECT biblioitemnumber,
907 WHERE biblioitemnumber IN (' . join( ',', @biblioitemnumbers ) . ')
909 return get_infos_of( $query, 'biblioitemnumber' );
912 =head1 FUNCTIONS FOR HANDLING MARC MANAGEMENT
914 =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
928 # cache for results of GetMarcStructure -- needed
930 our $marc_structure_cache;
932 sub GetMarcStructure {
933 my ( $forlibrarian, $frameworkcode ) = @_;
934 my $dbh=C4::Context->dbh;
935 $frameworkcode = "" unless $frameworkcode;
937 if (defined $marc_structure_cache and exists $marc_structure_cache->{$forlibrarian}->{$frameworkcode}) {
938 return $marc_structure_cache->{$forlibrarian}->{$frameworkcode};
941 my $sth = $dbh->prepare(
942 "SELECT COUNT(*) FROM marc_tag_structure WHERE frameworkcode=?");
943 $sth->execute($frameworkcode);
944 my ($total) = $sth->fetchrow;
945 $frameworkcode = "" unless ( $total > 0 );
946 $sth = $dbh->prepare(
947 "SELECT tagfield,liblibrarian,libopac,mandatory,repeatable
948 FROM marc_tag_structure
949 WHERE frameworkcode=?
952 $sth->execute($frameworkcode);
953 my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable );
955 while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) =
958 $res->{$tag}->{lib} =
959 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
960 $res->{$tag}->{tab} = "";
961 $res->{$tag}->{mandatory} = $mandatory;
962 $res->{$tag}->{repeatable} = $repeatable;
965 $sth = $dbh->prepare(
966 "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab,mandatory,repeatable,authorised_value,authtypecode,value_builder,kohafield,seealso,hidden,isurl,link,defaultvalue
967 FROM marc_subfield_structure
968 WHERE frameworkcode=?
969 ORDER BY tagfield,tagsubfield
973 $sth->execute($frameworkcode);
976 my $authorised_value;
988 $tag, $subfield, $liblibrarian,
990 $mandatory, $repeatable, $authorised_value,
991 $authtypecode, $value_builder, $kohafield,
992 $seealso, $hidden, $isurl,
998 $res->{$tag}->{$subfield}->{lib} =
999 ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac;
1000 $res->{$tag}->{$subfield}->{tab} = $tab;
1001 $res->{$tag}->{$subfield}->{mandatory} = $mandatory;
1002 $res->{$tag}->{$subfield}->{repeatable} = $repeatable;
1003 $res->{$tag}->{$subfield}->{authorised_value} = $authorised_value;
1004 $res->{$tag}->{$subfield}->{authtypecode} = $authtypecode;
1005 $res->{$tag}->{$subfield}->{value_builder} = $value_builder;
1006 $res->{$tag}->{$subfield}->{kohafield} = $kohafield;
1007 $res->{$tag}->{$subfield}->{seealso} = $seealso;
1008 $res->{$tag}->{$subfield}->{hidden} = $hidden;
1009 $res->{$tag}->{$subfield}->{isurl} = $isurl;
1010 $res->{$tag}->{$subfield}->{'link'} = $link;
1011 $res->{$tag}->{$subfield}->{defaultvalue} = $defaultvalue;
1014 $marc_structure_cache->{$forlibrarian}->{$frameworkcode} = $res;
1019 =head2 GetUsedMarcStructure
1021 the same function as GetMarcStructure except it just takes field
1022 in tab 0-9. (used field)
1024 my $results = GetUsedMarcStructure($frameworkcode);
1026 L<$results> is a ref to an array which each case containts a ref
1027 to a hash which each keys is the columns from marc_subfield_structure
1029 L<$frameworkcode> is the framework code.
1033 sub GetUsedMarcStructure($){
1034 my $frameworkcode = shift || '';
1037 FROM marc_subfield_structure
1039 AND frameworkcode = ?
1040 ORDER BY tagfield, tagsubfield
1042 my $sth = C4::Context->dbh->prepare($query);
1043 $sth->execute($frameworkcode);
1044 return $sth->fetchall_arrayref({});
1047 =head2 GetMarcFromKohaField
1051 ($MARCfield,$MARCsubfield)=GetMarcFromKohaField($kohafield,$frameworkcode);
1052 Returns the MARC fields & subfields mapped to the koha field
1053 for the given frameworkcode
1059 sub GetMarcFromKohaField {
1060 my ( $kohafield, $frameworkcode ) = @_;
1061 return 0, 0 unless $kohafield and defined $frameworkcode;
1062 my $relations = C4::Context->marcfromkohafield;
1064 $relations->{$frameworkcode}->{$kohafield}->[0],
1065 $relations->{$frameworkcode}->{$kohafield}->[1]
1069 =head2 GetMarcBiblio
1073 my $record = GetMarcBiblio($biblionumber);
1077 Returns MARC::Record representing bib identified by
1078 C<$biblionumber>. If no bib exists, returns undef.
1079 The MARC record contains both biblio & item data.
1084 my $biblionumber = shift;
1085 my $dbh = C4::Context->dbh;
1087 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1088 $sth->execute($biblionumber);
1089 my $row = $sth->fetchrow_hashref;
1090 my $marcxml = StripNonXmlChars($row->{'marcxml'});
1091 MARC::File::XML->default_record_format(C4::Context->preference('marcflavour'));
1092 my $record = MARC::Record->new();
1094 $record = eval {MARC::Record::new_from_xml( $marcxml, "utf8", C4::Context->preference('marcflavour'))};
1095 if ($@) {warn " problem with :$biblionumber : $@ \n$marcxml";}
1096 # $record = MARC::Record::new_from_usmarc( $marc) if $marc;
1107 my $marcxml = GetXmlBiblio($biblionumber);
1109 Returns biblioitems.marcxml of the biblionumber passed in parameter.
1110 The XML contains both biblio & item datas
1117 my ( $biblionumber ) = @_;
1118 my $dbh = C4::Context->dbh;
1120 $dbh->prepare("SELECT marcxml FROM biblioitems WHERE biblionumber=? ");
1121 $sth->execute($biblionumber);
1122 my ($marcxml) = $sth->fetchrow;
1126 =head2 GetCOinSBiblio
1130 my $coins = GetCOinSBiblio($biblionumber);
1132 Returns the COinS(a span) which can be included in a biblio record
1138 sub GetCOinSBiblio {
1139 my ( $biblionumber ) = @_;
1140 my $record = GetMarcBiblio($biblionumber);
1142 if (defined $record){
1143 # get the coin format
1144 my $pos7 = substr $record->leader(), 7,1;
1145 my $pos6 = substr $record->leader(), 6,1;
1148 my ($aulast, $aufirst) = ('','');
1157 if ( C4::Context->preference("marcflavour") eq "UNIMARC" ){
1162 'b' => 'manuscript',
1164 'd' => 'manuscript',
1168 'i' => 'audioRecording',
1169 'j' => 'audioRecording',
1172 'm' => 'computerProgram',
1177 'a' => 'journalArticle',
1181 $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book' ;
1183 if( $genre eq 'book' ){
1184 $genre = $fmts7->{$pos7} if $fmts7->{$pos7};
1187 ##### We must transform mtx to a valable mtx and document type ####
1188 if( $genre eq 'book' ){
1190 }elsif( $genre eq 'journal' ){
1192 }elsif( $genre eq 'journalArticle' ){
1199 $genre = ($mtx eq 'dc') ? "&rft.type=$genre" : "&rft.genre=$genre";
1202 $aulast = $record->subfield('700','a');
1203 $aufirst = $record->subfield('700','b');
1204 $oauthors = "&rft.au=$aufirst $aulast";
1206 if($record->field('200')){
1207 for my $au ($record->field('200')->subfield('g')){
1208 $oauthors .= "&rft.au=$au";
1211 $title = ( $mtx eq 'dc' ) ? "&rft.title=".$record->subfield('200','a') :
1212 "&rft.title=".$record->subfield('200','a')."&rft.btitle=".$record->subfield('200','a');
1213 $pubyear = $record->subfield('210','d');
1214 $publisher = $record->subfield('210','c');
1215 $isbn = $record->subfield('010','a');
1216 $issn = $record->subfield('011','a');
1218 # MARC21 need some improve
1221 $genre = "&rft.genre=book";
1224 if ($record->field('100')) {
1225 $oauthors .= "&rft.au=".$record->subfield('100','a');
1228 if($record->field('700')){
1229 for my $au ($record->field('700')->subfield('a')){
1230 $oauthors .= "&rft.au=$au";
1233 $title = "&rft.btitle=".$record->subfield('245','a');
1234 $subtitle = $record->subfield('245', 'b') || '';
1235 $title .= $subtitle;
1236 $pubyear = $record->subfield('260', 'c') || '';
1237 $publisher = $record->subfield('260', 'b') || '';
1238 $isbn = $record->subfield('020', 'a') || '';
1239 $issn = $record->subfield('022', 'a') || '';
1242 $coins_value = "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";
1243 $coins_value =~ s/\ /\+/g;
1244 #<!-- TMPL_VAR NAME="ocoins_format" -->&rft.au=<!-- TMPL_VAR NAME="author" -->&rft.btitle=<!-- TMPL_VAR NAME="title" -->&rft.date=<!-- TMPL_VAR NAME="publicationyear" -->&rft.pages=<!-- TMPL_VAR NAME="pages" -->&rft.isbn=<!-- TMPL_VAR NAME=amazonisbn -->&rft.aucorp=&rft.place=<!-- TMPL_VAR NAME="place" -->&rft.pub=<!-- TMPL_VAR NAME="publishercode" -->&rft.edition=<!-- TMPL_VAR NAME="edition" -->&rft.series=<!-- TMPL_VAR NAME="series" -->&rft.genre="
1246 return $coins_value;
1249 =head2 GetAuthorisedValueDesc
1253 my $subfieldvalue =get_authorised_value_desc(
1254 $tag, $subf[$i][0],$subf[$i][1], '', $taglib, $category);
1255 Retrieve the complete description for a given authorised value.
1257 Now takes $category and $value pair too.
1258 my $auth_value_desc =GetAuthorisedValueDesc(
1259 '','', 'DVD' ,'','','CCODE');
1265 sub GetAuthorisedValueDesc {
1266 my ( $tag, $subfield, $value, $framework, $tagslib, $category ) = @_;
1267 my $dbh = C4::Context->dbh;
1271 return $value unless defined $tagslib->{$tag}->{$subfield}->{'authorised_value'};
1274 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
1275 return C4::Branch::GetBranchName($value);
1279 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
1280 return getitemtypeinfo($value)->{description};
1283 #---- "true" authorized value
1284 $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'}
1287 if ( $category ne "" ) {
1290 "SELECT lib FROM authorised_values WHERE category = ? AND authorised_value = ?"
1292 $sth->execute( $category, $value );
1293 my $data = $sth->fetchrow_hashref;
1294 return $data->{'lib'};
1297 return $value; # if nothing is found return the original value
1305 $marcnotesarray = GetMarcNotes( $record, $marcflavour );
1306 Get all notes from the MARC record and returns them in an array.
1307 The note are stored in differents places depending on MARC flavour
1314 my ( $record, $marcflavour ) = @_;
1316 if ( $marcflavour eq "MARC21" ) {
1319 else { # assume unimarc if not marc21
1326 foreach my $field ( $record->field($scope) ) {
1327 my $value = $field->as_string();
1328 $value =~ s/\n/<br \/>/g ;
1330 if ( $note ne "" ) {
1331 $marcnote = { marcnote => $note, };
1332 push @marcnotes, $marcnote;
1335 if ( $note ne $value ) {
1336 $note = $note . " " . $value;
1341 $marcnote = { marcnote => $note };
1342 push @marcnotes, $marcnote; #load last tag into array
1345 } # end GetMarcNotes
1347 =head2 GetMarcSubjects
1351 $marcsubjcts = GetMarcSubjects($record,$marcflavour);
1352 Get all subjects from the MARC record and returns them in an array.
1353 The subjects are stored in differents places depending on MARC flavour
1359 sub GetMarcSubjects {
1360 my ( $record, $marcflavour ) = @_;
1361 my ( $mintag, $maxtag );
1362 if ( $marcflavour eq "MARC21" ) {
1366 else { # assume unimarc if not marc21
1376 foreach my $field ( $record->field('6..' )) {
1377 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1379 my @subfields = $field->subfields();
1382 # if there is an authority link, build the link with an= subfield9
1383 my $subfield9 = $field->subfield('9');
1384 for my $subject_subfield (@subfields ) {
1385 # don't load unimarc subfields 3,4,5
1386 next if (($marcflavour eq "UNIMARC") and ($subject_subfield->[0] =~ /3|4|5/ ) );
1387 # don't load MARC21 subfields 2 (FIXME: any more subfields??)
1388 next if (($marcflavour eq "MARC21") and ($subject_subfield->[0] =~ /2/ ) );
1389 my $code = $subject_subfield->[0];
1390 my $value = $subject_subfield->[1];
1391 my $linkvalue = $value;
1392 $linkvalue =~ s/(\(|\))//g;
1393 my $operator = " and " unless $counter==0;
1395 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1397 push @link_loop, {'limit' => 'su', link => $linkvalue, operator => $operator };
1399 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1401 my @this_link_loop = @link_loop;
1402 push @subfields_loop, {code => $code, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($subject_subfield->[0] eq 9 );
1406 push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop };
1409 return \@marcsubjects;
1410 } #end getMARCsubjects
1412 =head2 GetMarcAuthors
1416 authors = GetMarcAuthors($record,$marcflavour);
1417 Get all authors from the MARC record and returns them in an array.
1418 The authors are stored in differents places depending on MARC flavour
1424 sub GetMarcAuthors {
1425 my ( $record, $marcflavour ) = @_;
1426 my ( $mintag, $maxtag );
1427 # tagslib useful for UNIMARC author reponsabilities
1428 my $tagslib = &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.
1429 if ( $marcflavour eq "MARC21" ) {
1433 elsif ( $marcflavour eq "UNIMARC" ) { # assume unimarc if not marc21
1442 foreach my $field ( $record->fields ) {
1443 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
1446 my @subfields = $field->subfields();
1448 # if there is an authority link, build the link with Koha-Auth-Number: subfield9
1449 my $subfield9 = $field->subfield('9');
1450 for my $authors_subfield (@subfields) {
1451 # don't load unimarc subfields 3, 5
1452 next if ($marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~ /3|5/ ) );
1453 my $subfieldcode = $authors_subfield->[0];
1454 my $value = $authors_subfield->[1];
1455 my $linkvalue = $value;
1456 $linkvalue =~ s/(\(|\))//g;
1457 my $operator = " and " unless $count_auth==0;
1458 # if we have an authority link, use that as the link, otherwise use standard searching
1460 @link_loop = ({'limit' => 'an' ,link => "$subfield9" });
1463 # reset $linkvalue if UNIMARC author responsibility
1464 if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] eq "4")) {
1465 $linkvalue = "(".GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ).")";
1467 push @link_loop, {'limit' => 'au', link => $linkvalue, operator => $operator };
1469 $value = GetAuthorisedValueDesc( $field->tag(), $authors_subfield->[0], $authors_subfield->[1], '', $tagslib ) if ( $marcflavour eq 'UNIMARC' and ($authors_subfield->[0] =~/4/));
1470 my @this_link_loop = @link_loop;
1471 my $separator = C4::Context->preference("authoritysep") unless $count_auth==0;
1472 push @subfields_loop, {code => $subfieldcode, value => $value, link_loop => \@this_link_loop, separator => $separator} unless ($authors_subfield->[0] eq '9' );
1475 push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop };
1477 return \@marcauthors;
1484 $marcurls = GetMarcUrls($record,$marcflavour);
1485 Returns arrayref of URLs from MARC data, suitable to pass to tmpl loop.
1486 Assumes web resources (not uncommon in MARC21 to omit resource type ind)
1493 my ( $record, $marcflavour ) = @_;
1496 for my $field ( $record->field('856') ) {
1499 for my $note ( $field->subfield('z') ) {
1500 push @notes, { note => $note };
1502 my @urls = $field->subfield('u');
1503 foreach my $url (@urls) {
1504 if ( $marcflavour eq 'MARC21' ) {
1505 my $s3 = $field->subfield('3');
1506 my $link = $field->subfield('y');
1507 unless ( $url =~ /^\w+:/ ) {
1508 if ( $field->indicator(1) eq '7' ) {
1509 $url = $field->subfield('2') . "://" . $url;
1510 } elsif ( $field->indicator(1) eq '1' ) {
1511 $url = 'ftp://' . $url;
1513 # properly, this should be if ind1=4,
1514 # however we will assume http protocol since we're building a link.
1515 $url = 'http://' . $url;
1518 # TODO handle ind 2 (relationship)
1523 $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url;
1524 $marcurl->{'part'} = $s3 if ($link);
1525 $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^table/i );
1527 $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url;
1528 $marcurl->{'MARCURL'} = $url;
1530 push @marcurls, $marcurl;
1536 =head2 GetMarcSeries
1540 $marcseriesarray = GetMarcSeries($record,$marcflavour);
1541 Get all series from the MARC record and returns them in an array.
1542 The series are stored in differents places depending on MARC flavour
1549 my ($record, $marcflavour) = @_;
1550 my ($mintag, $maxtag);
1551 if ($marcflavour eq "MARC21") {
1554 } else { # assume unimarc if not marc21
1564 foreach my $field ($record->field('440'), $record->field('490')) {
1566 #my $value = $field->subfield('a');
1567 #$marcsubjct = {MARCSUBJCT => $value,};
1568 my @subfields = $field->subfields();
1569 #warn "subfields:".join " ", @$subfields;
1572 for my $series_subfield (@subfields) {
1574 undef $volume_number;
1575 # see if this is an instance of a volume
1576 if ($series_subfield->[0] eq 'v') {
1580 my $code = $series_subfield->[0];
1581 my $value = $series_subfield->[1];
1582 my $linkvalue = $value;
1583 $linkvalue =~ s/(\(|\))//g;
1584 my $operator = " and " unless $counter==0;
1585 push @link_loop, {link => $linkvalue, operator => $operator };
1586 my $separator = C4::Context->preference("authoritysep") unless $counter==0;
1587 if ($volume_number) {
1588 push @subfields_loop, {volumenum => $value};
1591 push @subfields_loop, {code => $code, value => $value, link_loop => \@link_loop, separator => $separator, volumenum => $volume_number};
1595 push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop };
1596 #$marcsubjct = {MARCSUBJCT => $field->as_string(),};
1597 #push @marcsubjcts, $marcsubjct;
1601 my $marcseriessarray=\@marcseries;
1602 return $marcseriessarray;
1603 } #end getMARCseriess
1605 =head2 GetFrameworkCode
1609 $frameworkcode = GetFrameworkCode( $biblionumber )
1615 sub GetFrameworkCode {
1616 my ( $biblionumber ) = @_;
1617 my $dbh = C4::Context->dbh;
1618 my $sth = $dbh->prepare("SELECT frameworkcode FROM biblio WHERE biblionumber=?");
1619 $sth->execute($biblionumber);
1620 my ($frameworkcode) = $sth->fetchrow;
1621 return $frameworkcode;
1624 =head2 GetPublisherNameFromIsbn
1626 $name = GetPublishercodeFromIsbn($isbn);
1633 sub GetPublisherNameFromIsbn($){
1635 $isbn =~ s/[- _]//g;
1637 my @codes = (split '-', DisplayISBN($isbn));
1638 my $code = $codes[0].$codes[1].$codes[2];
1639 my $dbh = C4::Context->dbh;
1641 SELECT distinct publishercode
1644 AND publishercode IS NOT NULL
1647 my $sth = $dbh->prepare($query);
1648 $sth->execute("$code%");
1649 my $name = $sth->fetchrow;
1650 return $name if length $name;
1654 =head2 TransformKohaToMarc
1658 $record = TransformKohaToMarc( $hash )
1659 This function builds partial MARC::Record from a hash
1660 Hash entries can be from biblio or biblioitems.
1661 This function is called in acquisition module, to create a basic catalogue entry from user entry
1667 sub TransformKohaToMarc {
1669 my $sth = C4::Context->dbh->prepare(
1670 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1672 my $record = MARC::Record->new();
1673 SetMarcUnicodeFlag($record, C4::Context->preference("marcflavour"));
1674 foreach (keys %{$hash}) {
1675 &TransformKohaToMarcOneField( $sth, $record, $_, $hash->{$_}, '' );
1680 =head2 TransformKohaToMarcOneField
1684 $record = TransformKohaToMarcOneField( $sth, $record, $kohafieldname, $value, $frameworkcode );
1690 sub TransformKohaToMarcOneField {
1691 my ( $sth, $record, $kohafieldname, $value, $frameworkcode ) = @_;
1692 $frameworkcode='' unless $frameworkcode;
1696 if ( !defined $sth ) {
1697 my $dbh = C4::Context->dbh;
1698 $sth = $dbh->prepare(
1699 "SELECT tagfield,tagsubfield FROM marc_subfield_structure WHERE frameworkcode=? AND kohafield=?"
1702 $sth->execute( $frameworkcode, $kohafieldname );
1703 if ( ( $tagfield, $tagsubfield ) = $sth->fetchrow ) {
1704 my $tag = $record->field($tagfield);
1706 $tag->update( $tagsubfield => $value );
1707 $record->delete_field($tag);
1708 $record->insert_fields_ordered($tag);
1711 $record->add_fields( $tagfield, " ", " ", $tagsubfield => $value );
1717 =head2 TransformHtmlToXml
1721 $xml = TransformHtmlToXml( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type )
1723 $auth_type contains :
1724 - nothing : rebuild a biblio, un UNIMARC the encoding is in 100$a pos 26/27
1725 - UNIMARCAUTH : rebuild an authority. In UNIMARC, the encoding is in 100$a pos 13/14
1726 - ITEM : rebuild an item : in UNIMARC, 100$a, it's in the biblio ! (otherwise, we would get 2 100 fields !)
1732 sub TransformHtmlToXml {
1733 my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_;
1734 my $xml = MARC::File::XML::header('UTF-8');
1735 $xml .= "<record>\n";
1736 $auth_type = C4::Context->preference('marcflavour') unless $auth_type;
1737 MARC::File::XML->default_record_format($auth_type);
1738 # in UNIMARC, field 100 contains the encoding
1739 # check that there is one, otherwise the
1740 # MARC::Record->new_from_xml will fail (and Koha will die)
1741 my $unimarc_and_100_exist=0;
1742 $unimarc_and_100_exist=1 if $auth_type eq 'ITEM'; # if we rebuild an item, no need of a 100 field
1747 @$indicator=map{sprintf("%2s",$_) unless ( length($_)<2)}@$indicator;
1748 for ( my $i = 0 ; $i < @$tags ; $i++ ) {
1749 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and @$tags[$i] eq "100" and @$subfields[$i] eq "a") {
1750 # if we have a 100 field and it's values are not correct, skip them.
1751 # if we don't have any valid 100 field, we will create a default one at the end
1752 my $enc = substr( @$values[$i], 26, 2 );
1753 if ($enc eq '01' or $enc eq '50' or $enc eq '03') {
1754 $unimarc_and_100_exist=1;
1759 @$values[$i] =~ s/&/&/g;
1760 @$values[$i] =~ s/</</g;
1761 @$values[$i] =~ s/>/>/g;
1762 @$values[$i] =~ s/"/"/g;
1763 @$values[$i] =~ s/'/'/g;
1764 # if ( !utf8::is_utf8( @$values[$i] ) ) {
1765 # utf8::decode( @$values[$i] );
1767 if ( ( @$tags[$i] ne $prevtag ) ) {
1768 $j++ unless ( @$tags[$i] eq "" );
1770 $xml .= "</datafield>\n";
1771 if ( ( @$tags[$i] && @$tags[$i] > 10 )
1772 && ( @$values[$i] ne "" ) )
1774 my $ind1 = _default_ind_to_space(substr( @$indicator[$j], 0, 1 ));
1776 if ( @$indicator[$j] ) {
1777 $ind2 = _default_ind_to_space(substr( @$indicator[$j], 1, 1 ));
1780 warn "Indicator in @$tags[$i] is empty";
1783 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1784 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1792 if ( @$values[$i] ne "" ) {
1795 if ( @$tags[$i] eq "000" ) {
1796 $xml .= "<leader>@$values[$i]</leader>\n";
1799 # rest of the fixed fields
1801 elsif ( @$tags[$i] < 10 ) {
1802 $xml .= "<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
1806 my $ind1 = _default_ind_to_space( substr( @$indicator[$j], 0, 1 ) );
1807 my $ind2 = _default_ind_to_space( substr( @$indicator[$j], 1, 1 ) );
1808 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1809 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1815 else { # @$tags[$i] eq $prevtag
1816 if ( @$values[$i] eq "" ) {
1820 my $ind1 = _default_ind_to_space( substr( @$indicator[$j], 0, 1 ) );
1821 my $ind2 = _default_ind_to_space( substr( @$indicator[$j], 1, 1 ) );
1822 $xml .= "<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
1825 $xml .= "<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
1828 $prevtag = @$tags[$i];
1830 $xml .= "</datafield>\n" if @$tags > 0;
1831 if (C4::Context->preference('marcflavour') eq 'UNIMARC' and !$unimarc_and_100_exist) {
1832 # warn "SETTING 100 for $auth_type";
1833 my $string = strftime( "%Y%m%d", localtime(time) );
1834 # set 50 to position 26 is biblios, 13 if authorities
1836 $pos=13 if $auth_type eq 'UNIMARCAUTH';
1837 $string = sprintf( "%-*s", 35, $string );
1838 substr( $string, $pos , 6, "50" );
1839 $xml .= "<datafield tag=\"100\" ind1=\"\" ind2=\"\">\n";
1840 $xml .= "<subfield code=\"a\">$string</subfield>\n";
1841 $xml .= "</datafield>\n";
1843 $xml .= "</record>\n";
1844 $xml .= MARC::File::XML::footer();
1848 =head2 _default_ind_to_space
1850 Passed what should be an indicator returns a space
1851 if its undefined or zero length
1855 sub _default_ind_to_space {
1857 if (!defined $s || $s eq q{}) {
1863 =head2 TransformHtmlToMarc
1865 L<$record> = TransformHtmlToMarc(L<$params>,L<$cgi>)
1866 L<$params> is a ref to an array as below:
1868 'tag_010_indicator1_531951' ,
1869 'tag_010_indicator2_531951' ,
1870 'tag_010_code_a_531951_145735' ,
1871 'tag_010_subfield_a_531951_145735' ,
1872 'tag_200_indicator1_873510' ,
1873 'tag_200_indicator2_873510' ,
1874 'tag_200_code_a_873510_673465' ,
1875 'tag_200_subfield_a_873510_673465' ,
1876 'tag_200_code_b_873510_704318' ,
1877 'tag_200_subfield_b_873510_704318' ,
1878 'tag_200_code_e_873510_280822' ,
1879 'tag_200_subfield_e_873510_280822' ,
1880 'tag_200_code_f_873510_110730' ,
1881 'tag_200_subfield_f_873510_110730' ,
1883 L<$cgi> is the CGI object which containts the value.
1884 L<$record> is the MARC::Record object.
1888 sub TransformHtmlToMarc {
1892 # explicitly turn on the UTF-8 flag for all
1893 # 'tag_' parameters to avoid incorrect character
1894 # conversion later on
1895 my $cgi_params = $cgi->Vars;
1896 foreach my $param_name (keys %$cgi_params) {
1897 if ($param_name =~ /^tag_/) {
1898 my $param_value = $cgi_params->{$param_name};
1899 if (utf8::decode($param_value)) {
1900 $cgi_params->{$param_name} = $param_value;
1902 # FIXME - need to do something if string is not valid UTF-8
1906 # creating a new record
1907 my $record = MARC::Record->new();
1910 while ($params->[$i]){ # browse all CGI params
1911 my $param = $params->[$i];
1913 # if we are on biblionumber, store it in the MARC::Record (it may not be in the edited fields)
1914 if ($param eq 'biblionumber') {
1915 my ( $biblionumbertagfield, $biblionumbertagsubfield ) =
1916 &GetMarcFromKohaField( "biblio.biblionumber", '' );
1917 if ($biblionumbertagfield < 10) {
1918 $newfield = MARC::Field->new(
1919 $biblionumbertagfield,
1920 $cgi->param($param),
1923 $newfield = MARC::Field->new(
1924 $biblionumbertagfield,
1927 "$biblionumbertagsubfield" => $cgi->param($param),
1930 push @fields,$newfield if($newfield);
1932 elsif ($param =~ /^tag_(\d*)_indicator1_/){ # new field start when having 'input name="..._indicator1_..."
1935 my $ind1 = _default_ind_to_space(substr($cgi->param($param), 0, 1));
1936 my $ind2 = _default_ind_to_space(substr($cgi->param($params->[$i+1]), 0, 1));
1940 if($tag < 10){ # no code for theses fields
1941 # in MARC editor, 000 contains the leader.
1942 if ($tag eq '000' ) {
1943 $record->leader($cgi->param($params->[$j+1])) if length($cgi->param($params->[$j+1]))==24;
1944 # between 001 and 009 (included)
1945 } elsif ($cgi->param($params->[$j+1]) ne '') {
1946 $newfield = MARC::Field->new(
1948 $cgi->param($params->[$j+1]),
1951 # > 009, deal with subfields
1953 while(defined $params->[$j] && $params->[$j] =~ /_code_/){ # browse all it's subfield
1954 my $inner_param = $params->[$j];
1956 if($cgi->param($params->[$j+1]) ne ''){ # only if there is a value (code => value)
1957 $newfield->add_subfields(
1958 $cgi->param($inner_param) => $cgi->param($params->[$j+1])
1962 if ( $cgi->param($params->[$j+1]) ne '' ) { # creating only if there is a value (code => value)
1963 $newfield = MARC::Field->new(
1967 $cgi->param($inner_param) => $cgi->param($params->[$j+1]),
1974 push @fields,$newfield if($newfield);
1979 $record->append_fields(@fields);
1983 # cache inverted MARC field map
1984 our $inverted_field_map;
1986 =head2 TransformMarcToKoha
1990 $result = TransformMarcToKoha( $dbh, $record, $frameworkcode )
1994 Extract data from a MARC bib record into a hashref representing
1995 Koha biblio, biblioitems, and items fields.
1998 sub TransformMarcToKoha {
1999 my ( $dbh, $record, $frameworkcode, $limit_table ) = @_;
2002 $limit_table=$limit_table||0;
2003 $frameworkcode = '' unless defined $frameworkcode;
2005 unless (defined $inverted_field_map) {
2006 $inverted_field_map = _get_inverted_marc_field_map();
2010 if ( defined $limit_table && $limit_table eq 'items') {
2011 $tables{'items'} = 1;
2013 $tables{'items'} = 1;
2014 $tables{'biblio'} = 1;
2015 $tables{'biblioitems'} = 1;
2018 # traverse through record
2019 MARCFIELD: foreach my $field ($record->fields()) {
2020 my $tag = $field->tag();
2021 next MARCFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag};
2022 if ($field->is_control_field()) {
2023 my $kohafields = $inverted_field_map->{$frameworkcode}->{$tag}->{list};
2024 ENTRY: foreach my $entry (@{ $kohafields }) {
2025 my ($subfield, $table, $column) = @{ $entry };
2026 next ENTRY unless exists $tables{$table};
2027 my $key = _disambiguate($table, $column);
2028 if ($result->{$key}) {
2029 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($field->data() eq "")) {
2030 $result->{$key} .= " | " . $field->data();
2033 $result->{$key} = $field->data();
2037 # deal with subfields
2038 MARCSUBFIELD: foreach my $sf ($field->subfields()) {
2039 my $code = $sf->[0];
2040 next MARCSUBFIELD unless exists $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code};
2041 my $value = $sf->[1];
2042 SFENTRY: foreach my $entry (@{ $inverted_field_map->{$frameworkcode}->{$tag}->{sfs}->{$code} }) {
2043 my ($table, $column) = @{ $entry };
2044 next SFENTRY unless exists $tables{$table};
2045 my $key = _disambiguate($table, $column);
2046 if ($result->{$key}) {
2047 unless (($key eq "biblionumber" or $key eq "biblioitemnumber") and ($value eq "")) {
2048 $result->{$key} .= " | " . $value;
2051 $result->{$key} = $value;
2058 # modify copyrightdate to keep only the 1st year found
2059 if (exists $result->{'copyrightdate'}) {
2060 my $temp = $result->{'copyrightdate'};
2061 $temp =~ m/c(\d\d\d\d)/;
2062 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2063 $result->{'copyrightdate'} = $1;
2065 else { # if no cYYYY, get the 1st date.
2066 $temp =~ m/(\d\d\d\d)/;
2067 $result->{'copyrightdate'} = $1;
2071 # modify publicationyear to keep only the 1st year found
2072 if (exists $result->{'publicationyear'}) {
2073 my $temp = $result->{'publicationyear'};
2074 if ( $temp =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first
2075 $result->{'publicationyear'} = $1;
2077 else { # if no cYYYY, get the 1st date.
2078 $temp =~ m/(\d\d\d\d)/;
2079 $result->{'publicationyear'} = $1;
2086 sub _get_inverted_marc_field_map {
2088 my $relations = C4::Context->marcfromkohafield;
2090 foreach my $frameworkcode (keys %{ $relations }) {
2091 foreach my $kohafield (keys %{ $relations->{$frameworkcode} }) {
2092 next unless @{ $relations->{$frameworkcode}->{$kohafield} }; # not all columns are mapped to MARC tag & subfield
2093 my $tag = $relations->{$frameworkcode}->{$kohafield}->[0];
2094 my $subfield = $relations->{$frameworkcode}->{$kohafield}->[1];
2095 my ($table, $column) = split /[.]/, $kohafield, 2;
2096 push @{ $field_map->{$frameworkcode}->{$tag}->{list} }, [ $subfield, $table, $column ];
2097 push @{ $field_map->{$frameworkcode}->{$tag}->{sfs}->{$subfield} }, [ $table, $column ];
2103 =head2 _disambiguate
2107 $newkey = _disambiguate($table, $field);
2109 This is a temporary hack to distinguish between the
2110 following sets of columns when using TransformMarcToKoha.
2112 items.cn_source & biblioitems.cn_source
2113 items.cn_sort & biblioitems.cn_sort
2115 Columns that are currently NOT distinguished (FIXME
2116 due to lack of time to fully test) are:
2118 biblio.notes and biblioitems.notes
2123 FIXME - this is necessary because prefixing each column
2124 name with the table name would require changing lots
2125 of code and templates, and exposing more of the DB
2126 structure than is good to the UI templates, particularly
2127 since biblio and bibloitems may well merge in a future
2128 version. In the future, it would also be good to
2129 separate DB access and UI presentation field names
2136 sub CountItemsIssued {
2137 my ( $biblionumber ) = @_;
2138 my $dbh = C4::Context->dbh;
2139 my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?');
2140 $sth->execute( $biblionumber );
2141 my $row = $sth->fetchrow_hashref();
2142 return $row->{'issuedCount'};
2146 my ($table, $column) = @_;
2147 if ($column eq "cn_sort" or $column eq "cn_source") {
2148 return $table . '.' . $column;
2155 =head2 get_koha_field_from_marc
2159 $result->{_disambiguate($table, $field)} = get_koha_field_from_marc($table,$field,$record,$frameworkcode);
2161 Internal function to map data from the MARC record to a specific non-MARC field.
2162 FIXME: this is meant to replace TransformMarcToKohaOneField after more testing.
2168 sub get_koha_field_from_marc {
2169 my ($koha_table,$koha_column,$record,$frameworkcode) = @_;
2170 my ( $tagfield, $subfield ) = GetMarcFromKohaField( $koha_table.'.'.$koha_column, $frameworkcode );
2172 foreach my $field ( $record->field($tagfield) ) {
2173 if ( $field->tag() < 10 ) {
2175 $kohafield .= " | " . $field->data();
2178 $kohafield = $field->data();
2182 if ( $field->subfields ) {
2183 my @subfields = $field->subfields();
2184 foreach my $subfieldcount ( 0 .. $#subfields ) {
2185 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2188 " | " . $subfields[$subfieldcount][1];
2192 $subfields[$subfieldcount][1];
2203 =head2 TransformMarcToKohaOneField
2207 $result = TransformMarcToKohaOneField( $kohatable, $kohafield, $record, $result, $frameworkcode )
2213 sub TransformMarcToKohaOneField {
2215 # FIXME ? if a field has a repeatable subfield that is used in old-db,
2216 # only the 1st will be retrieved...
2217 my ( $kohatable, $kohafield, $record, $result, $frameworkcode ) = @_;
2219 my ( $tagfield, $subfield ) =
2220 GetMarcFromKohaField( $kohatable . "." . $kohafield,
2222 foreach my $field ( $record->field($tagfield) ) {
2223 if ( $field->tag() < 10 ) {
2224 if ( $result->{$kohafield} ) {
2225 $result->{$kohafield} .= " | " . $field->data();
2228 $result->{$kohafield} = $field->data();
2232 if ( $field->subfields ) {
2233 my @subfields = $field->subfields();
2234 foreach my $subfieldcount ( 0 .. $#subfields ) {
2235 if ( $subfields[$subfieldcount][0] eq $subfield ) {
2236 if ( $result->{$kohafield} ) {
2237 $result->{$kohafield} .=
2238 " | " . $subfields[$subfieldcount][1];
2241 $result->{$kohafield} =
2242 $subfields[$subfieldcount][1];
2252 =head1 OTHER FUNCTIONS
2255 =head2 PrepareItemrecordDisplay
2259 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber);
2261 Returns a hash with all the fields for Display a given item data in a template
2267 sub PrepareItemrecordDisplay {
2269 my ( $bibnum, $itemnum, $defaultvalues ) = @_;
2271 my $dbh = C4::Context->dbh;
2272 my $today_iso = C4::Dates->today('iso');
2273 my $frameworkcode = &GetFrameworkCode( $bibnum );
2274 my ( $itemtagfield, $itemtagsubfield ) =
2275 &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2276 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2277 my $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum) if ($itemnum);
2278 # FIXME : I'd rather have GetMarcBiblio called out of this.
2279 # Since it gets the whole Biblio record for each item
2280 my $marcrecord = GetMarcBiblio( $bibnum) if ($bibnum);
2282 my $authorised_values_sth =
2284 "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib"
2286 foreach my $tag ( sort keys %{$tagslib} ) {
2287 my $previous_tag = '';
2289 # loop through each subfield
2291 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2292 next if ( subfield_is_koha_internal_p($subfield) );
2293 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2295 $subfield_data{tag} = $tag;
2296 $subfield_data{subfield} = $subfield;
2297 $subfield_data{countsubfield} = $cntsubf++;
2298 $subfield_data{kohafield} =
2299 $tagslib->{$tag}->{$subfield}->{'kohafield'};
2301 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2302 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2303 $subfield_data{mandatory} =
2304 $tagslib->{$tag}->{$subfield}->{mandatory};
2305 $subfield_data{repeatable} =
2306 $tagslib->{$tag}->{$subfield}->{repeatable};
2307 $subfield_data{hidden} = "display:none"
2308 if $tagslib->{$tag}->{$subfield}->{hidden};
2311 ( $x, $value ) = _find_value( $tag, $subfield, $itemrecord );
2314 $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
2315 $value ||= $defaultvalues->{$tagslib->{$tag}->{$subfield}->{'kohafield'}};
2316 # get today date & replace YYYY, MM, DD if provided in the default value
2317 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
2318 $value =~ s/YYYY/$year/g;
2319 $value =~ s/MM/$month/g;
2320 $value =~ s/DD/$day/g;
2322 $value =~ s/"/"/g;
2324 # search for itemcallnumber if applicable
2325 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2326 'items.itemcallnumber'
2327 && C4::Context->preference('itemcallnumber') )
2330 substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2332 substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2333 my $temp = $marcrecord->field($CNtag) if ($marcrecord);
2335 $value = $temp->subfield($CNsubfield);
2338 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq
2339 'items.itemcallnumber'
2340 && $defaultvalues->{'callnumber'} )
2342 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2344 $value = $defaultvalues->{'callnumber'};
2347 if ( ($tagslib->{$tag}->{$subfield}->{kohafield} eq
2348 'items.holdingbranch' ||
2349 $tagslib->{$tag}->{$subfield}->{kohafield} eq
2351 && $defaultvalues->{'branchcode'} )
2353 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2355 $value = $defaultvalues->{branchcode};
2358 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2359 my @authorised_values;
2362 # builds list, depending on authorised value...
2364 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq
2367 if ( ( C4::Context->preference("IndependantBranches") )
2368 && ( C4::Context->userenv->{flags} != 1 ) )
2372 "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"
2374 $sth->execute( C4::Context->userenv->{branch} );
2375 push @authorised_values, ""
2377 $tagslib->{$tag}->{$subfield}->{mandatory} );
2378 while ( my ( $branchcode, $branchname ) =
2379 $sth->fetchrow_array )
2381 push @authorised_values, $branchcode;
2382 $authorised_lib{$branchcode} = $branchname;
2388 "SELECT branchcode,branchname FROM branches ORDER BY branchname"
2391 push @authorised_values, ""
2393 $tagslib->{$tag}->{$subfield}->{mandatory} );
2394 while ( my ( $branchcode, $branchname ) =
2395 $sth->fetchrow_array )
2397 push @authorised_values, $branchcode;
2398 $authorised_lib{$branchcode} = $branchname;
2404 elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq
2409 "SELECT itemtype,description FROM itemtypes ORDER BY description"
2412 push @authorised_values, ""
2413 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2414 while ( my ( $itemtype, $description ) =
2415 $sth->fetchrow_array )
2417 push @authorised_values, $itemtype;
2418 $authorised_lib{$itemtype} = $description;
2421 #---- "true" authorised value
2424 $authorised_values_sth->execute(
2425 $tagslib->{$tag}->{$subfield}->{authorised_value} );
2426 push @authorised_values, ""
2427 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2428 while ( my ( $value, $lib ) =
2429 $authorised_values_sth->fetchrow_array )
2431 push @authorised_values, $value;
2432 $authorised_lib{$value} = $lib;
2435 $subfield_data{marc_value} = CGI::scrolling_list(
2436 -name => 'field_value',
2437 -values => \@authorised_values,
2438 -default => "$value",
2439 -labels => \%authorised_lib,
2446 $subfield_data{marc_value} =
2447 "<input type=\"text\" name=\"field_value\" value=\"$value\" size=\"50\" maxlength=\"255\" />";
2449 push( @loop_data, \%subfield_data );
2453 my $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield )
2454 if ( $itemrecord && $itemrecord->field($itemtagfield) );
2456 'itemtagfield' => $itemtagfield,
2457 'itemtagsubfield' => $itemtagsubfield,
2458 'itemnumber' => $itemnumber,
2459 'iteminformation' => \@loop_data
2465 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2467 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2468 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2469 # =head2 ModZebrafiles
2471 # &ModZebrafiles( $dbh, $biblionumber, $record, $folder, $server );
2475 # sub ModZebrafiles {
2477 # my ( $dbh, $biblionumber, $record, $folder, $server ) = @_;
2481 # C4::Context->zebraconfig($server)->{directory} . "/" . $folder . "/";
2482 # unless ( opendir( DIR, "$zebradir" ) ) {
2483 # warn "$zebradir not found";
2487 # my $filename = $zebradir . $biblionumber;
2490 # open( OUTPUT, ">", $filename . ".xml" );
2491 # print OUTPUT $record;
2500 ModZebra( $biblionumber, $op, $server, $oldRecord, $newRecord );
2502 $biblionumber is the biblionumber we want to index
2503 $op is specialUpdate or delete, and is used to know what we want to do
2504 $server is the server that we want to update
2505 $oldRecord is the MARC::Record containing the previous version of the record. This is used only when
2506 NoZebra=1, as NoZebra indexing needs to know the previous version of a record in order to
2508 $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.
2515 ###Accepts a $server variable thus we can use it for biblios authorities or other zebra dbs
2516 my ( $biblionumber, $op, $server, $oldRecord, $newRecord ) = @_;
2517 my $dbh=C4::Context->dbh;
2519 # true ModZebra commented until indexdata fixes zebraDB crashes (it seems they occur on multiple updates
2521 # replaced by a zebraqueue table, that is filled with ModZebra to run.
2522 # the table is emptied by misc/cronjobs/zebraqueue_start.pl script
2524 if (C4::Context->preference("NoZebra")) {
2525 # lock the nozebra table : we will read index lines, update them in Perl process
2526 # and write everything in 1 transaction.
2527 # lock the table to avoid someone else overwriting what we are doing
2528 $dbh->do('LOCK TABLES nozebra WRITE,biblio WRITE,biblioitems WRITE, systempreferences WRITE, auth_types WRITE, auth_header WRITE, auth_subfield_structure READ');
2529 my %result; # the result hash that will be built by deletion / add, and written on mySQL at the end, to improve speed
2530 if ($op eq 'specialUpdate') {
2531 # OK, we have to add or update the record
2532 # 1st delete (virtually, in indexes), if record actually exists
2534 %result = _DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2536 # ... add the record
2537 %result=_AddBiblioNoZebra($biblionumber,$newRecord, $server, %result);
2539 # it's a deletion, delete the record...
2540 # warn "DELETE the record $biblionumber on $server".$record->as_formatted;
2541 %result=_DelBiblioNoZebra($biblionumber,$oldRecord,$server);
2543 # ok, now update the database...
2544 my $sth = $dbh->prepare("UPDATE nozebra SET biblionumbers=? WHERE server=? AND indexname=? AND value=?");
2545 foreach my $key (keys %result) {
2546 foreach my $index (keys %{$result{$key}}) {
2547 $sth->execute($result{$key}->{$index}, $server, $key, $index);
2550 $dbh->do('UNLOCK TABLES');
2553 # we use zebra, just fill zebraqueue table
2555 my $check_sql = "SELECT COUNT(*) FROM zebraqueue
2557 AND biblio_auth_number = ?
2560 my $check_sth = $dbh->prepare_cached($check_sql);
2561 $check_sth->execute($server, $biblionumber, $op);
2562 my ($count) = $check_sth->fetchrow_array;
2563 $check_sth->finish();
2565 my $sth=$dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,server,operation) VALUES(?,?,?)");
2566 $sth->execute($biblionumber,$server,$op);
2572 =head2 GetNoZebraIndexes
2574 %indexes = GetNoZebraIndexes;
2576 return the data from NoZebraIndexes syspref.
2580 sub GetNoZebraIndexes {
2581 my $no_zebra_indexes = C4::Context->preference('NoZebraIndexes');
2583 INDEX: foreach my $line (split /['"],[\n\r]*/,$no_zebra_indexes) {
2584 $line =~ /(.*)=>(.*)/;
2585 my $index = $1; # initial ' or " is removed afterwards
2587 $index =~ s/'|"|\s//g;
2588 $fields =~ s/'|"|\s//g;
2589 $indexes{$index}=$fields;
2594 =head1 INTERNAL FUNCTIONS
2596 =head2 _DelBiblioNoZebra($biblionumber,$record,$server);
2598 function to delete a biblio in NoZebra indexes
2599 This function does NOT delete anything in database : it reads all the indexes entries
2600 that have to be deleted & delete them in the hash
2601 The SQL part is done either :
2602 - after the Add if we are modifying a biblio (delete + add again)
2603 - immediatly after this sub if we are doing a true deletion.
2604 $server can be 'biblioserver' or 'authorityserver' : it indexes biblios or authorities (in the same table, $server being part of the table itself
2609 sub _DelBiblioNoZebra {
2610 my ($biblionumber, $record, $server)=@_;
2613 my $dbh = C4::Context->dbh;
2617 if ($server eq 'biblioserver') {
2618 %index=GetNoZebraIndexes;
2619 # get title of the record (to store the 10 first letters with the index)
2620 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title','');
2621 $title = lc($record->subfield($titletag,$titlesubfield));
2623 # for authorities, the "title" is the $a mainentry
2624 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2625 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2626 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2627 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2628 $index{'mainmainentry'}= $authref->{'auth_tag_to_report'}.'a';
2629 $index{'mainentry'} = $authref->{'auth_tag_to_report'}.'*';
2630 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2634 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2635 $title =~ s/ |,|;|\[|\]|\(|\)|\*|-|'|=//g;
2636 # limit to 10 char, should be enough, and limit the DB size
2637 $title = substr($title,0,10);
2639 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2640 foreach my $field ($record->fields()) {
2641 #parse each subfield
2642 next if $field->tag <10;
2643 foreach my $subfield ($field->subfields()) {
2644 my $tag = $field->tag();
2645 my $subfieldcode = $subfield->[0];
2647 # check each index to see if the subfield is stored somewhere
2648 # otherwise, store it in __RAW__ index
2649 foreach my $key (keys %index) {
2650 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2651 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2653 my $line= lc $subfield->[1];
2654 # remove meaningless value in the field...
2655 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2656 # ... and split in words
2657 foreach (split / /,$line) {
2658 next unless $_; # skip empty values (multiple spaces)
2659 # if the entry is already here, do nothing, the biblionumber has already be removed
2660 unless ( defined( $result{$key}->{$_} ) && ( $result{$key}->{$_} =~ /$biblionumber,$title\-(\d);/) ) {
2661 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2662 $sth2->execute($server,$key,$_);
2663 my $existing_biblionumbers = $sth2->fetchrow;
2665 if ($existing_biblionumbers) {
2666 # warn " existing for $key $_: $existing_biblionumbers";
2667 $result{$key}->{$_} =$existing_biblionumbers;
2668 $result{$key}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2674 # the subfield is not indexed, store it in __RAW__ index anyway
2676 my $line= lc $subfield->[1];
2677 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:/ /g;
2678 # ... and split in words
2679 foreach (split / /,$line) {
2680 next unless $_; # skip empty values (multiple spaces)
2681 # if the entry is already here, do nothing, the biblionumber has already be removed
2682 unless ($result{'__RAW__'}->{$_} =~ /$biblionumber,$title\-(\d);/) {
2683 # get the index value if it exist in the nozebra table and remove the entry, otherwise, do nothing
2684 $sth2->execute($server,'__RAW__',$_);
2685 my $existing_biblionumbers = $sth2->fetchrow;
2687 if ($existing_biblionumbers) {
2688 $result{'__RAW__'}->{$_} =$existing_biblionumbers;
2689 $result{'__RAW__'}->{$_} =~ s/$biblionumber,$title\-(\d);//;
2699 =head2 _AddBiblioNoZebra($biblionumber, $record, $server, %result);
2701 function to add a biblio in NoZebra indexes
2705 sub _AddBiblioNoZebra {
2706 my ($biblionumber, $record, $server, %result)=@_;
2707 my $dbh = C4::Context->dbh;
2711 if ($server eq 'biblioserver') {
2712 %index=GetNoZebraIndexes;
2713 # get title of the record (to store the 10 first letters with the index)
2714 my ($titletag,$titlesubfield) = GetMarcFromKohaField('biblio.title','');
2715 $title = lc($record->subfield($titletag,$titlesubfield));
2717 # warn "server : $server";
2718 # for authorities, the "title" is the $a mainentry
2719 my ($auth_type_tag, $auth_type_sf) = C4::AuthoritiesMarc::get_auth_type_location();
2720 my $authref = C4::AuthoritiesMarc::GetAuthType($record->subfield($auth_type_tag, $auth_type_sf));
2721 warn "ERROR : authtype undefined for ".$record->as_formatted unless $authref;
2722 $title = $record->subfield($authref->{auth_tag_to_report},'a');
2723 $index{'mainmainentry'} = $authref->{auth_tag_to_report}.'a';
2724 $index{'mainentry'} = $authref->{auth_tag_to_report}.'*';
2725 $index{'auth_type'} = "${auth_type_tag}${auth_type_sf}";
2728 # remove blancks comma (that could cause problem when decoding the string for CQL retrieval) and regexp specific values
2729 $title =~ s/ |\.|,|;|\[|\]|\(|\)|\*|-|'|:|=|\r|\n//g;
2730 # limit to 10 char, should be enough, and limit the DB size
2731 $title = substr($title,0,10);
2733 my $sth2=$dbh->prepare('SELECT biblionumbers FROM nozebra WHERE server=? AND indexname=? AND value=?');
2734 foreach my $field ($record->fields()) {
2735 #parse each subfield
2736 ###FIXME: impossible to index a 001-009 value with NoZebra
2737 next if $field->tag <10;
2738 foreach my $subfield ($field->subfields()) {
2739 my $tag = $field->tag();
2740 my $subfieldcode = $subfield->[0];
2742 # warn "INDEXING :".$subfield->[1];
2743 # check each index to see if the subfield is stored somewhere
2744 # otherwise, store it in __RAW__ index
2745 foreach my $key (keys %index) {
2746 # warn "examining $key index : ".$index{$key}." for $tag $subfieldcode";
2747 if ($index{$key} =~ /$tag\*/ or $index{$key} =~ /$tag$subfieldcode/) {
2749 my $line= lc $subfield->[1];
2750 # remove meaningless value in the field...
2751 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2752 # ... and split in words
2753 foreach (split / /,$line) {
2754 next unless $_; # skip empty values (multiple spaces)
2755 # if the entry is already here, improve weight
2756 # warn "managing $_";
2757 if ( exists $result{$key}->{$_} && $result{$key}->{"$_"} =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2758 my $weight = $1 + 1;
2759 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2760 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2762 # get the value if it exist in the nozebra table, otherwise, create it
2763 $sth2->execute($server,$key,$_);
2764 my $existing_biblionumbers = $sth2->fetchrow;
2766 if ($existing_biblionumbers) {
2767 $result{$key}->{"$_"} =$existing_biblionumbers;
2768 my $weight = defined $1 ? $1 + 1 : 1;
2769 $result{$key}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//g;
2770 $result{$key}->{"$_"} .= "$biblionumber,$title-$weight;";
2771 # create a new ligne for this entry
2773 # warn "INSERT : $server / $key / $_";
2774 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname='.$dbh->quote($key).',value='.$dbh->quote($_));
2775 $result{$key}->{"$_"}.="$biblionumber,$title-1;";
2781 # the subfield is not indexed, store it in __RAW__ index anyway
2783 my $line= lc $subfield->[1];
2784 $line =~ s/-|\.|\?|,|;|!|'|\(|\)|\[|\]|{|}|"|<|>|&|\+|\*|\/|=|:|\r|\n/ /g;
2785 # ... and split in words
2786 foreach (split / /,$line) {
2787 next unless $_; # skip empty values (multiple spaces)
2788 # if the entry is already here, improve weight
2789 my $tmpstr = $result{'__RAW__'}->{"$_"} || "";
2790 if ($tmpstr =~ /$biblionumber,\Q$title\E\-(\d+);/) {
2792 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2793 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2795 # get the value if it exist in the nozebra table, otherwise, create it
2796 $sth2->execute($server,'__RAW__',$_);
2797 my $existing_biblionumbers = $sth2->fetchrow;
2799 if ($existing_biblionumbers) {
2800 $result{'__RAW__'}->{"$_"} =$existing_biblionumbers;
2801 my $weight = ($1 ? $1 : 0) + 1;
2802 $result{'__RAW__'}->{"$_"} =~ s/$biblionumber,\Q$title\E\-(\d+);//;
2803 $result{'__RAW__'}->{"$_"} .= "$biblionumber,$title-$weight;";
2804 # create a new ligne for this entry
2806 $dbh->do('INSERT INTO nozebra SET server='.$dbh->quote($server).', indexname="__RAW__",value='.$dbh->quote($_));
2807 $result{'__RAW__'}->{"$_"}.="$biblionumber,$title-1;";
2822 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2824 Find the given $subfield in the given $tag in the given
2825 MARC::Record $record. If the subfield is found, returns
2826 the (indicators, value) pair; otherwise, (undef, undef) is
2830 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2831 I suggest we export it from this module.
2838 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2841 if ( $tagfield < 10 ) {
2842 if ( $record->field($tagfield) ) {
2843 push @result, $record->field($tagfield)->data();
2850 foreach my $field ( $record->field($tagfield) ) {
2851 my @subfields = $field->subfields();
2852 foreach my $subfield (@subfields) {
2853 if ( @$subfield[0] eq $insubfield ) {
2854 push @result, @$subfield[1];
2855 $indicator = $field->indicator(1) . $field->indicator(2);
2860 return ( $indicator, @result );
2863 =head2 _koha_marc_update_bib_ids
2867 _koha_marc_update_bib_ids($record, $frameworkcode, $biblionumber, $biblioitemnumber);
2869 Internal function to add or update biblionumber and biblioitemnumber to
2876 sub _koha_marc_update_bib_ids {
2877 my ($record, $frameworkcode, $biblionumber, $biblioitemnumber) = @_;
2879 # we must add bibnum and bibitemnum in MARC::Record...
2880 # we build the new field with biblionumber and biblioitemnumber
2881 # we drop the original field
2882 # we add the new builded field.
2883 my ($biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber",$frameworkcode);
2884 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber",$frameworkcode);
2886 if ($biblio_tag != $biblioitem_tag) {
2887 # biblionumber & biblioitemnumber are in different fields
2889 # deal with biblionumber
2890 my ($new_field, $old_field);
2891 if ($biblio_tag < 10) {
2892 $new_field = MARC::Field->new( $biblio_tag, $biblionumber );
2895 MARC::Field->new( $biblio_tag, '', '',
2896 "$biblio_subfield" => $biblionumber );
2899 # drop old field and create new one...
2900 $old_field = $record->field($biblio_tag);
2901 $record->delete_field($old_field) if $old_field;
2902 $record->append_fields($new_field);
2904 # deal with biblioitemnumber
2905 if ($biblioitem_tag < 10) {
2906 $new_field = MARC::Field->new( $biblioitem_tag, $biblioitemnumber, );
2909 MARC::Field->new( $biblioitem_tag, '', '',
2910 "$biblioitem_subfield" => $biblioitemnumber, );
2912 # drop old field and create new one...
2913 $old_field = $record->field($biblioitem_tag);
2914 $record->delete_field($old_field) if $old_field;
2915 $record->insert_fields_ordered($new_field);
2918 # biblionumber & biblioitemnumber are in the same field (can't be <10 as fields <10 have only 1 value)
2919 my $new_field = MARC::Field->new(
2920 $biblio_tag, '', '',
2921 "$biblio_subfield" => $biblionumber,
2922 "$biblioitem_subfield" => $biblioitemnumber
2925 # drop old field and create new one...
2926 my $old_field = $record->field($biblio_tag);
2927 $record->delete_field($old_field) if $old_field;
2928 $record->insert_fields_ordered($new_field);
2932 =head2 _koha_marc_update_biblioitem_cn_sort
2936 _koha_marc_update_biblioitem_cn_sort($marc, $biblioitem, $frameworkcode);
2940 Given a MARC bib record and the biblioitem hash, update the
2941 subfield that contains a copy of the value of biblioitems.cn_sort.
2945 sub _koha_marc_update_biblioitem_cn_sort {
2947 my $biblioitem = shift;
2948 my $frameworkcode= shift;
2950 my ($biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort",$frameworkcode);
2951 return unless $biblioitem_tag;
2953 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
2955 if (my $field = $marc->field($biblioitem_tag)) {
2956 $field->delete_subfield(code => $biblioitem_subfield);
2957 if ($cn_sort ne '') {
2958 $field->add_subfields($biblioitem_subfield => $cn_sort);
2961 # if we get here, no biblioitem tag is present in the MARC record, so
2962 # we'll create it if $cn_sort is not empty -- this would be
2963 # an odd combination of events, however
2965 $marc->insert_grouped_field(MARC::Field->new($biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort));
2970 =head2 _koha_add_biblio
2974 my ($biblionumber,$error) = _koha_add_biblio($dbh,$biblioitem);
2976 Internal function to add a biblio ($biblio is a hash with the values)
2982 sub _koha_add_biblio {
2983 my ( $dbh, $biblio, $frameworkcode ) = @_;
2987 # set the series flag
2989 if ( $biblio->{'seriestitle'} ) { $serial = 1 };
2993 SET frameworkcode = ?,
3004 my $sth = $dbh->prepare($query);
3007 $biblio->{'author'},
3009 $biblio->{'unititle'},
3012 $biblio->{'seriestitle'},
3013 $biblio->{'copyrightdate'},
3014 $biblio->{'abstract'}
3017 my $biblionumber = $dbh->{'mysql_insertid'};
3018 if ( $dbh->errstr ) {
3019 $error.="ERROR in _koha_add_biblio $query".$dbh->errstr;
3024 #warn "LEAVING _koha_add_biblio: ".$biblionumber."\n";
3025 return ($biblionumber,$error);
3028 =head2 _koha_modify_biblio
3032 my ($biblionumber,$error) == _koha_modify_biblio($dbh,$biblio,$frameworkcode);
3034 Internal function for updating the biblio table
3040 sub _koha_modify_biblio {
3041 my ( $dbh, $biblio, $frameworkcode ) = @_;
3046 SET frameworkcode = ?,
3055 WHERE biblionumber = ?
3058 my $sth = $dbh->prepare($query);
3062 $biblio->{'author'},
3064 $biblio->{'unititle'},
3066 $biblio->{'serial'},
3067 $biblio->{'seriestitle'},
3068 $biblio->{'copyrightdate'},
3069 $biblio->{'abstract'},
3070 $biblio->{'biblionumber'}
3071 ) if $biblio->{'biblionumber'};
3073 if ( $dbh->errstr || !$biblio->{'biblionumber'} ) {
3074 $error.="ERROR in _koha_modify_biblio $query".$dbh->errstr;
3077 return ( $biblio->{'biblionumber'},$error );
3080 =head2 _koha_modify_biblioitem_nonmarc
3084 my ($biblioitemnumber,$error) = _koha_modify_biblioitem_nonmarc( $dbh, $biblioitem );
3086 Updates biblioitems row except for marc and marcxml, which should be changed
3093 sub _koha_modify_biblioitem_nonmarc {
3094 my ( $dbh, $biblioitem ) = @_;
3097 # re-calculate the cn_sort, it may have changed
3098 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3102 SET biblionumber = ?,
3108 publicationyear = ?,
3112 collectiontitle = ?,
3114 collectionvolume= ?,
3115 editionstatement= ?,
3116 editionresponsibility = ?,
3130 where biblioitemnumber = ?
3132 my $sth = $dbh->prepare($query);
3134 $biblioitem->{'biblionumber'},
3135 $biblioitem->{'volume'},
3136 $biblioitem->{'number'},
3137 $biblioitem->{'itemtype'},
3138 $biblioitem->{'isbn'},
3139 $biblioitem->{'issn'},
3140 $biblioitem->{'publicationyear'},
3141 $biblioitem->{'publishercode'},
3142 $biblioitem->{'volumedate'},
3143 $biblioitem->{'volumedesc'},
3144 $biblioitem->{'collectiontitle'},
3145 $biblioitem->{'collectionissn'},
3146 $biblioitem->{'collectionvolume'},
3147 $biblioitem->{'editionstatement'},
3148 $biblioitem->{'editionresponsibility'},
3149 $biblioitem->{'illus'},
3150 $biblioitem->{'pages'},
3151 $biblioitem->{'bnotes'},
3152 $biblioitem->{'size'},
3153 $biblioitem->{'place'},
3154 $biblioitem->{'lccn'},
3155 $biblioitem->{'url'},
3156 $biblioitem->{'biblioitems.cn_source'},
3157 $biblioitem->{'cn_class'},
3158 $biblioitem->{'cn_item'},
3159 $biblioitem->{'cn_suffix'},
3161 $biblioitem->{'totalissues'},
3162 $biblioitem->{'biblioitemnumber'}
3164 if ( $dbh->errstr ) {
3165 $error.="ERROR in _koha_modify_biblioitem_nonmarc $query".$dbh->errstr;
3168 return ($biblioitem->{'biblioitemnumber'},$error);
3171 =head2 _koha_add_biblioitem
3175 my ($biblioitemnumber,$error) = _koha_add_biblioitem( $dbh, $biblioitem );
3177 Internal function to add a biblioitem
3183 sub _koha_add_biblioitem {
3184 my ( $dbh, $biblioitem ) = @_;
3187 my ($cn_sort) = GetClassSort($biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} );
3189 "INSERT INTO biblioitems SET
3196 publicationyear = ?,
3200 collectiontitle = ?,
3202 collectionvolume= ?,
3203 editionstatement= ?,
3204 editionresponsibility = ?,
3220 my $sth = $dbh->prepare($query);
3222 $biblioitem->{'biblionumber'},
3223 $biblioitem->{'volume'},
3224 $biblioitem->{'number'},
3225 $biblioitem->{'itemtype'},
3226 $biblioitem->{'isbn'},
3227 $biblioitem->{'issn'},
3228 $biblioitem->{'publicationyear'},
3229 $biblioitem->{'publishercode'},
3230 $biblioitem->{'volumedate'},
3231 $biblioitem->{'volumedesc'},
3232 $biblioitem->{'collectiontitle'},
3233 $biblioitem->{'collectionissn'},
3234 $biblioitem->{'collectionvolume'},
3235 $biblioitem->{'editionstatement'},
3236 $biblioitem->{'editionresponsibility'},
3237 $biblioitem->{'illus'},
3238 $biblioitem->{'pages'},
3239 $biblioitem->{'bnotes'},
3240 $biblioitem->{'size'},
3241 $biblioitem->{'place'},
3242 $biblioitem->{'lccn'},
3243 $biblioitem->{'marc'},
3244 $biblioitem->{'url'},
3245 $biblioitem->{'biblioitems.cn_source'},
3246 $biblioitem->{'cn_class'},
3247 $biblioitem->{'cn_item'},
3248 $biblioitem->{'cn_suffix'},
3250 $biblioitem->{'totalissues'}
3252 my $bibitemnum = $dbh->{'mysql_insertid'};
3253 if ( $dbh->errstr ) {
3254 $error.="ERROR in _koha_add_biblioitem $query".$dbh->errstr;
3258 return ($bibitemnum,$error);
3261 =head2 _koha_delete_biblio
3265 $error = _koha_delete_biblio($dbh,$biblionumber);
3267 Internal sub for deleting from biblio table -- also saves to deletedbiblio
3269 C<$dbh> - the database handle
3270 C<$biblionumber> - the biblionumber of the biblio to be deleted
3276 # FIXME: add error handling
3278 sub _koha_delete_biblio {
3279 my ( $dbh, $biblionumber ) = @_;
3281 # get all the data for this biblio
3282 my $sth = $dbh->prepare("SELECT * FROM biblio WHERE biblionumber=?");
3283 $sth->execute($biblionumber);
3285 if ( my $data = $sth->fetchrow_hashref ) {
3287 # save the record in deletedbiblio
3288 # find the fields to save
3289 my $query = "INSERT INTO deletedbiblio SET ";
3291 foreach my $temp ( keys %$data ) {
3292 $query .= "$temp = ?,";
3293 push( @bind, $data->{$temp} );
3296 # replace the last , by ",?)"
3298 my $bkup_sth = $dbh->prepare($query);
3299 $bkup_sth->execute(@bind);
3303 my $del_sth = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?");
3304 $del_sth->execute($biblionumber);
3311 =head2 _koha_delete_biblioitems
3315 $error = _koha_delete_biblioitems($dbh,$biblioitemnumber);
3317 Internal sub for deleting from biblioitems table -- also saves to deletedbiblioitems
3319 C<$dbh> - the database handle
3320 C<$biblionumber> - the biblioitemnumber of the biblioitem to be deleted
3326 # FIXME: add error handling
3328 sub _koha_delete_biblioitems {
3329 my ( $dbh, $biblioitemnumber ) = @_;
3331 # get all the data for this biblioitem
3333 $dbh->prepare("SELECT * FROM biblioitems WHERE biblioitemnumber=?");
3334 $sth->execute($biblioitemnumber);
3336 if ( my $data = $sth->fetchrow_hashref ) {
3338 # save the record in deletedbiblioitems
3339 # find the fields to save
3340 my $query = "INSERT INTO deletedbiblioitems SET ";
3342 foreach my $temp ( keys %$data ) {
3343 $query .= "$temp = ?,";
3344 push( @bind, $data->{$temp} );
3347 # replace the last , by ",?)"
3349 my $bkup_sth = $dbh->prepare($query);
3350 $bkup_sth->execute(@bind);
3353 # delete the biblioitem
3355 $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?");
3356 $del_sth->execute($biblioitemnumber);
3363 =head1 UNEXPORTED FUNCTIONS
3365 =head2 ModBiblioMarc
3367 &ModBiblioMarc($newrec,$biblionumber,$frameworkcode);
3369 Add MARC data for a biblio to koha
3371 Function exported, but should NOT be used, unless you really know what you're doing
3377 # pass the MARC::Record to this function, and it will create the records in the marc field
3378 my ( $record, $biblionumber, $frameworkcode ) = @_;
3379 my $dbh = C4::Context->dbh;
3380 my @fields = $record->fields();
3381 if ( !$frameworkcode ) {
3382 $frameworkcode = "";
3385 $dbh->prepare("UPDATE biblio SET frameworkcode=? WHERE biblionumber=?");
3386 $sth->execute( $frameworkcode, $biblionumber );
3388 my $encoding = C4::Context->preference("marcflavour");
3390 # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode
3391 if ( $encoding eq "UNIMARC" ) {
3392 my $string = $record->subfield( 100, "a" );
3393 if ( ($string) && ( length($record->subfield( 100, "a" )) == 35 ) ) {
3394 my $f100 = $record->field(100);
3395 $record->delete_field($f100);
3398 $string = POSIX::strftime( "%Y%m%d", localtime );
3400 $string = sprintf( "%-*s", 35, $string );
3402 substr( $string, 22, 6, "frey50" );
3403 unless ( $record->subfield( 100, "a" ) ) {
3404 $record->insert_grouped_field(
3405 MARC::Field->new( 100, "", "", "a" => $string ) );
3409 if (C4::Context->preference("NoZebra")) {
3410 # only NoZebra indexing needs to have
3411 # the previous version of the record
3412 $oldRecord = GetMarcBiblio($biblionumber);
3416 "UPDATE biblioitems SET marc=?,marcxml=? WHERE biblionumber=?");
3417 $sth->execute( $record->as_usmarc(), $record->as_xml_record($encoding),
3420 ModZebra($biblionumber,"specialUpdate","biblioserver",$oldRecord,$record);
3421 return $biblionumber;
3424 =head2 z3950_extended_services
3426 z3950_extended_services($serviceType,$serviceOptions,$record);
3428 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.
3430 C<$serviceType> one of: itemorder,create,drop,commit,update,xmlupdate
3432 C<$serviceOptions> a has of key/value pairs. For instance, if service_type is 'update', $service_options should contain:
3434 action => update action, one of specialUpdate, recordInsert, recordReplace, recordDelete, elementUpdate.
3438 recordidOpaque => Opaque Record ID (user supplied) or recordidNumber => Record ID number (system number).
3439 syntax => the record syntax (transfer syntax)
3440 databaseName = Database from connection object
3442 To set serviceOptions, call set_service_options($serviceType)
3444 C<$record> the record, if one is needed for the service type
3446 A record should be in XML. You can convert it to XML from MARC by running it through marc2xml().
3450 sub z3950_extended_services {
3451 my ( $server, $serviceType, $action, $serviceOptions ) = @_;
3453 # get our connection object
3454 my $Zconn = C4::Context->Zconn( $server, 0, 1 );
3456 # create a new package object
3457 my $Zpackage = $Zconn->package();
3460 $Zpackage->option( action => $action );
3462 if ( $serviceOptions->{'databaseName'} ) {
3463 $Zpackage->option( databaseName => $serviceOptions->{'databaseName'} );
3465 if ( $serviceOptions->{'recordIdNumber'} ) {
3467 recordIdNumber => $serviceOptions->{'recordIdNumber'} );
3469 if ( $serviceOptions->{'recordIdOpaque'} ) {
3471 recordIdOpaque => $serviceOptions->{'recordIdOpaque'} );
3474 # this is an ILL request (Zebra doesn't support it, but Koha could eventually)
3475 #if ($serviceType eq 'itemorder') {
3476 # $Zpackage->option('contact-name' => $serviceOptions->{'contact-name'});
3477 # $Zpackage->option('contact-phone' => $serviceOptions->{'contact-phone'});
3478 # $Zpackage->option('contact-email' => $serviceOptions->{'contact-email'});
3479 # $Zpackage->option('itemorder-item' => $serviceOptions->{'itemorder-item'});
3482 if ( $serviceOptions->{record} ) {
3483 $Zpackage->option( record => $serviceOptions->{record} );
3485 # can be xml or marc
3486 if ( $serviceOptions->{'syntax'} ) {
3487 $Zpackage->option( syntax => $serviceOptions->{'syntax'} );
3491 # send the request, handle any exception encountered
3492 eval { $Zpackage->send($serviceType) };
3493 if ( $@ && $@->isa("ZOOM::Exception") ) {
3494 return "error: " . $@->code() . " " . $@->message() . "\n";
3497 # free up package resources
3498 $Zpackage->destroy();
3501 =head2 set_service_options
3503 my $serviceOptions = set_service_options($serviceType);
3505 C<$serviceType> itemorder,create,drop,commit,update,xmlupdate
3507 Currently, we only support 'create', 'commit', and 'update'. 'drop' support will be added as soon as Zebra supports it.
3511 sub set_service_options {
3512 my ($serviceType) = @_;
3515 # FIXME: This needs to be an OID ... if we ever need 'syntax' this sub will need to change
3516 # $serviceOptions->{ 'syntax' } = ''; #zebra doesn't support syntaxes other than xml
3518 if ( $serviceType eq 'commit' ) {
3522 if ( $serviceType eq 'create' ) {
3526 if ( $serviceType eq 'drop' ) {
3527 die "ERROR: 'drop' not currently supported (by Zebra)";
3529 return $serviceOptions;
3532 =head3 get_biblio_authorised_values
3534 find the types and values for all authorised values assigned to this biblio.
3538 MARC::Record of the bib
3540 returns: a hashref mapping the authorised value to the value set for this biblionumber
3542 $authorised_values = {
3543 'Scent' => 'flowery',
3544 'Audience' => 'Young Adult',
3545 'itemtypes' => 'SER',
3548 Notes: forlibrarian should probably be passed in, and called something different.
3553 sub get_biblio_authorised_values {
3554 my $biblionumber = shift;
3557 my $forlibrarian = 1; # are we in staff or opac?
3558 my $frameworkcode = GetFrameworkCode( $biblionumber );
3560 my $authorised_values;
3562 my $tagslib = GetMarcStructure( $forlibrarian, $frameworkcode )
3563 or return $authorised_values;
3565 # assume that these entries in the authorised_value table are bibliolevel.
3566 # ones that start with 'item%' are item level.
3567 my $query = q(SELECT distinct authorised_value, kohafield
3568 FROM marc_subfield_structure
3569 WHERE authorised_value !=''
3570 AND (kohafield like 'biblio%'
3571 OR kohafield like '') );
3572 my $bibliolevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
3574 foreach my $tag ( keys( %$tagslib ) ) {
3575 foreach my $subfield ( keys( %{$tagslib->{ $tag }} ) ) {
3576 # warn "checking $subfield. type is: " . ref $tagslib->{ $tag }{ $subfield };
3577 if ( 'HASH' eq ref $tagslib->{ $tag }{ $subfield } ) {
3578 if ( defined $tagslib->{ $tag }{ $subfield }{'authorised_value'} && exists $bibliolevel_authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } ) {
3579 if ( defined $record->field( $tag ) ) {
3580 my $this_subfield_value = $record->field( $tag )->subfield( $subfield );
3581 if ( defined $this_subfield_value ) {
3582 $authorised_values->{ $tagslib->{ $tag }{ $subfield }{'authorised_value'} } = $this_subfield_value;
3589 # warn ( Data::Dumper->Dump( [ $authorised_values ], [ 'authorised_values' ] ) );
3590 return $authorised_values;
3600 Koha Developement team <info@koha.org>
3602 Paul POULAIN paul.poulain@free.fr
3604 Joshua Ferraro jmf@liblime.com