3 # Copyright 2006 (C) LibLime
4 # Joshua Ferraro <jmf@liblime.com>
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA 02111-1307 USA
22 use strict
;# use warnings; #FIXME: turn off warnings before release
24 # please specify in which methods a given module is used
25 use MARC
::Record
; # marc2marcxml, marcxml2marc, html2marc, changeEncoding
26 use MARC
::File
::XML
; # marc2marcxml, marcxml2marc, html2marcxml, changeEncoding
27 use MARC
::Crosswalk
::DublinCore
; # marc2dcxml
28 use Biblio
::EndnoteStyle
;
29 use Unicode
::Normalize
; # _entity_encode
32 use C4
::Biblio
; #marc2bibtex
33 use C4
::Csv
; #marc2csv
34 use Text
::CSV
; #marc2csv
36 use vars
qw($VERSION @ISA @EXPORT);
38 # set the version for version checking
43 # only export API methods
62 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
66 New in Koha 3.x. This module handles all record-related management functions.
68 =head1 API (EXPORTED FUNCTIONS)
70 =head2 marc2marc - Convert from one flavour of ISO-2709 to another
74 my ($error,$newmarc) = marc2marc($marc,$to_flavour,$from_flavour,$encoding);
76 Returns an ISO-2709 scalar
83 my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
84 my $error = "Feature not yet implemented\n";
85 return ($error,$marc);
88 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
92 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
94 Returns a MARCXML scalar
98 C<$marc> - an ISO-2709 scalar or MARC::Record object
100 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
102 C<$flavour> - MARC21 or UNIMARC
104 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
113 my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
114 my $error; # the error string
115 my $marcxml; # the final MARCXML scalar
117 # test if it's already a MARC::Record object, if not, make it one
119 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
120 $marc_record_obj = $marc;
121 } else { # it's not a MARC::Record object, make it one
122 eval { $marc_record_obj = MARC
::Record
->new_from_usmarc($marc) }; # handle exceptions
124 # conversion to MARC::Record object failed, populate $error
125 if ($@
) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File
::ERROR
};
127 # only proceed if no errors so far
130 # check the record for warnings
131 my @warnings = $marc_record_obj->warnings();
133 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
134 foreach my $warn (@warnings) { warn "\t".$warn };
136 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
137 unless($flavour) {$flavour = C4
::Context
->preference("marcflavour")}; # set default MARC flavour
139 # attempt to convert the record to MARCXML
140 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
142 # record creation failed, populate $error
144 $error .= "Creation of MARCXML failed:".$MARC::File
::ERROR
;
145 $error .= "Additional information:\n";
146 my @warnings = $@
->warnings();
147 foreach my $warn (@warnings) { $error.=$warn."\n" };
149 # record creation was successful
152 # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block
153 @warnings = $marc_record_obj->warnings();
155 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
156 foreach my $warn (@warnings) { warn "\t".$warn };
160 # only proceed if no errors so far
163 # entity encode the XML unless instructed not to
164 unless ($dont_entity_encode) {
165 my ($marcxml_entity_encoded) = _entity_encode
($marcxml);
166 $marcxml = $marcxml_entity_encoded;
170 # return result to calling program
171 return ($error,$marcxml);
174 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
178 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
180 Returns an ISO-2709 scalar
184 C<$marcxml> - a MARCXML record
186 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
188 C<$flavour> - MARC21 or UNIMARC
197 my ($marcxml,$encoding,$flavour) = @_;
198 my $error; # the error string
199 my $marc; # the final ISO-2709 scalar
200 unless($encoding) {$encoding = "UTF-8"}; # set the default encoding
201 unless($flavour) {$flavour = C4
::Context
->preference("marcflavour")}; # set the default MARC flavour
203 # attempt to do the conversion
204 eval { $marc = MARC
::Record
->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
206 # record creation failed, populate $error
207 if ($@
) {$error .="\nCreation of MARCXML Record failed: ".$@
;
208 $error.=$MARC::File
::ERROR
if ($MARC::File
::ERROR
);
210 # return result to calling program
211 return ($error,$marc);
214 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
218 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
220 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
222 FIXME: should return actual XML, not just an object
226 C<$marc> - an ISO-2709 scalar or MARC::Record object
228 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
237 my ($marc,$qualified) = @_;
239 # test if it's already a MARC::Record object, if not, make it one
241 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
242 $marc_record_obj = $marc;
243 } else { # it's not a MARC::Record object, make it one
244 eval { $marc_record_obj = MARC
::Record
->new_from_usmarc($marc) }; # handle exceptions
246 # conversion to MARC::Record object failed, populate $error
248 $error .="\nCreation of MARC::Record object failed: ".$MARC::File
::ERROR
;
251 my $crosswalk = MARC
::Crosswalk
::DublinCore
->new;
253 $crosswalk = MARC
::Crosswalk
::DublinCore
->new( qualified
=> 1 );
255 my $dcxml = $crosswalk->as_dublincore($marc_record_obj);
256 my $dcxmlfinal = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
257 $dcxmlfinal .= "<metadata
258 xmlns=\"http://example.org/myapp/\"
259 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
260 xsi:schemaLocation=\"http://example.org/myapp/ http://example.org/myapp/schema.xsd\"
261 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
262 xmlns:dcterms=\"http://purl.org/dc/terms/\">";
264 foreach my $element ( $dcxml->elements() ) {
265 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name().">\n";
267 $dcxmlfinal .= "\n</metadata>";
268 return ($error,$dcxmlfinal);
270 =head2 marc2modsxml - Convert from ISO-2709 to MODS
274 my ($error,$modsxml) = marc2modsxml($marc);
276 Returns a MODS scalar
284 # grab the XML, run it through our stylesheet, push it out to the browser
285 my $xmlrecord = marc2marcxml
($marc);
286 my $xslfile = C4
::Context
->config('intrahtdocs')."/prog/en/xslt/MARC21slim2MODS3-1.xsl";
287 my $parser = XML
::LibXML
->new();
288 my $xslt = XML
::LibXSLT
->new();
289 my $source = $parser->parse_string($xmlrecord);
290 my $style_doc = $parser->parse_file($xslfile);
291 my $stylesheet = $xslt->parse_stylesheet($style_doc);
292 my $results = $stylesheet->transform($source);
293 my $newxmlrecord = $stylesheet->output_string($results);
294 return ($newxmlrecord);
299 my $marc_rec_obj = MARC
::Record
->new_from_usmarc($marc);
300 my $f260 = $marc_rec_obj->field('260');
301 my $f260a = $f260->subfield('a') if $f260;
302 my $f710 = $marc_rec_obj->field('710');
303 my $f710a = $f710->subfield('a') if $f710;
304 my $f500 = $marc_rec_obj->field('500');
305 my $abstract = $f500->subfield('a') if $f500;
307 DB
=> C4
::Context
->preference("LibraryName"),
308 Title
=> $marc_rec_obj->title(),
309 Author
=> $marc_rec_obj->author(),
312 Year
=> $marc_rec_obj->publication_date,
313 Abstract
=> $abstract,
316 my $style = new Biblio
::EndnoteStyle
();
318 $template.= "DB - DB\n" if C4
::Context
->preference("LibraryName");
319 $template.="T1 - Title\n" if $marc_rec_obj->title();
320 $template.="A1 - Author\n" if $marc_rec_obj->author();
321 $template.="PB - Publisher\n" if $f710a;
322 $template.="CY - City\n" if $f260a;
323 $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
324 $template.="AB - Abstract\n" if $abstract;
325 my ($text, $errmsg) = $style->format($template, $fields);
330 =head2 marc2csv - Convert from UNIMARC to CSV
334 my ($csv) = marc2csv($record, $csvprofileid);
340 C<$record> - a MARC::Record object
342 C<$csvprofileid> - the id of the CSV profile to use for the export (see export_format.export_format_id and the GetCsvProfiles function in C4::Csv)
352 my ($record, $id, $header) = @_;
354 my $csv = Text
::CSV
->new();
356 # Get the information about the csv profile
357 my $marcfieldslist = GetMarcFieldsForCsv
($id);
359 # Getting the marcfields as an array
360 my @marcfields = split('\|', $marcfieldslist);
362 # If we have to insert the headers
364 my @marcfieldsheaders;
366 my $dbh = C4
::Context
->dbh;
368 # For each field or subfield
369 foreach (@marcfields) {
370 # We get the matching tag name
371 if (index($_, '$') > 0) {
372 my ($fieldtag, $subfieldtag) = split('\$', $_);
373 my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
374 my $sth = $dbh->prepare($query);
375 $sth->execute($fieldtag, $subfieldtag);
376 my @results = $sth->fetchrow_array();
377 push @marcfieldsheaders, $results[0];
379 my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
380 my $sth = $dbh->prepare($query);
382 my @results = $sth->fetchrow_array();
383 push @marcfieldsheaders, $results[0];
386 $csv->combine(@marcfieldsheaders);
387 $output = $csv->string() . "\n";
390 # For each marcfield to export
392 foreach my $marcfield (@marcfields) {
393 # If it is a subfield
394 if (index($marcfield, '$') > 0) {
395 my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
396 my @fields = $record->field($fieldtag);
400 foreach my $field (@fields) {
402 # We take every matching subfield
403 my @subfields = $field->subfield($subfieldtag);
404 foreach my $subfield (@subfields) {
405 push @tmpfields, $subfield;
408 push (@fieldstab, join(',', @tmpfields));
411 my @fields = ($record->field($marcfield));
412 push (@fieldstab, join(',', map($_->as_string(), @fields)));
416 $csv->combine(@fieldstab);
417 $output .= $csv->string() . "\n";
428 my ($error,$marcxml) = html2marcxml($tags,$subfields,$values,$indicator,$ind_tag);
430 Returns a MARCXML scalar
432 this is used in addbiblio.pl and additem.pl to build the MARCXML record from
435 FIXME: this could use some better code documentation
442 my ($tags,$subfields,$values,$indicator,$ind_tag) = @_;
444 # add the header info
445 my $marcxml= MARC
::File
::XML
::header
(C4
::Context
->preference('TemplateEncoding'),C4
::Context
->preference('marcflavour'));
447 # some flags used to figure out where in the record we are
453 # handle characters that would cause the parser to choke FIXME: is there a more elegant solution?
454 for (my $i=0;$i<=@
$tags;$i++){
455 @
$values[$i] =~ s/&/&/g;
456 @
$values[$i] =~ s/</</g;
457 @
$values[$i] =~ s/>/>/g;
458 @
$values[$i] =~ s/"/"/g;
459 @
$values[$i] =~ s/'/'/g;
461 if ((@
$tags[$i] ne $prevtag)){
462 $j++ unless (@
$tags[$i] eq "");
463 #warn "IND:".substr(@$indicator[$j],0,1).substr(@$indicator[$j],1,1)." ".@$tags[$i];
465 $marcxml.="</datafield>\n";
466 if ((@
$tags[$i] > 10) && (@
$values[$i] ne "")){
467 my $ind1 = substr(@
$indicator[$j],0,1);
468 my $ind2 = substr(@
$indicator[$j],1,1);
469 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
470 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
476 if (@
$values[$i] ne "") {
478 if (@
$tags[$i] eq "000") {
479 $marcxml.="<leader>@$values[$i]</leader>\n";
481 # rest of the fixed fields
482 } elsif (@
$tags[$i] lt '010') { # don't compare numerically 010 == 8
483 $marcxml.="<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
486 my $ind1 = substr(@
$indicator[$j],0,1);
487 my $ind2 = substr(@
$indicator[$j],1,1);
488 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
489 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
494 } else { # @$tags[$i] eq $prevtag
495 if (@
$values[$i] eq "") {
498 my $ind1 = substr(@
$indicator[$j],0,1);
499 my $ind2 = substr(@
$indicator[$j],1,1);
500 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
503 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
506 $prevtag = @
$tags[$i];
508 $marcxml.= MARC
::File
::XML
::footer
();
510 return ($error,$marcxml);
517 Probably best to avoid using this ... it has some rather striking problems:
521 * saves blank subfields
523 * subfield order is hardcoded to always start with 'a' for repeatable tags (because it is hardcoded in the addfield routine).
525 * only possible to specify one set of indicators for each set of tags (ie, one for all the 650s). (because they were stored in a hash with the tag as the key).
527 * the underlying routines didn't support subfield reordering or subfield repeatability.
531 I've left it in here because it could be useful if someone took the time to fix it. -- kados
538 my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
540 my $record = MARC
::Record
->new();
541 # my %subfieldlist=();
542 my $prevvalue; # if tag <10
543 my $field; # if tag >=10
544 for (my $i=0; $i< @
$rtags; $i++) {
545 # rebuild MARC::Record
546 # warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
547 if (@
$rtags[$i] ne $prevtag) {
550 if (($prevtag ne '000') && ($prevvalue ne "")) {
551 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
552 } elsif ($prevvalue ne ""){
553 $record->leader($prevvalue);
557 if (($field) && ($field ne "")) {
558 $record->add_fields($field);
561 $indicators{@
$rtags[$i]}.=' ';
562 # skip blank tags, I hope this works
563 if (@
$rtags[$i] eq ''){
564 $prevtag = @
$rtags[$i];
568 if (@
$rtags[$i] <10) {
569 $prevvalue= @
$rvalues[$i];
573 if (@
$rvalues[$i] eq "") {
576 $field = MARC
::Field
->new( (sprintf "%03s",@
$rtags[$i]), substr($indicators{@
$rtags[$i]},0,1),substr($indicators{@
$rtags[$i]},1,1), @
$rsubfields[$i] => @
$rvalues[$i]);
578 # warn "1=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
580 $prevtag = @
$rtags[$i];
582 if (@
$rtags[$i] <10) {
583 $prevvalue=@
$rvalues[$i];
585 if (length(@
$rvalues[$i])>0) {
586 $field->add_subfields(@
$rsubfields[$i] => @
$rvalues[$i]);
587 # warn "2=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
590 $prevtag= @
$rtags[$i];
594 # the last has not been included inside the loop... do it now !
596 #warn Dumper($field->{_subfields});
597 $record->add_fields($field) if (($field) && $field ne "");
598 #warn "HTML2MARC=".$record->as_formatted;
602 =head2 changeEncoding - Change the encoding of a record
606 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
608 Changes the encoding of a record
612 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
614 C<$format> - MARC or MARCXML (required)
616 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
618 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
620 C<$from_encoding> - the encoding the record is currently in (optional, it will probably be able to tell unless there's a problem with the record)
624 FIXME: the from_encoding doesn't work yet
626 FIXME: better handling for UNIMARC, it should allow management of 100 field
628 FIXME: shouldn't have to convert to and from xml/marc just to change encoding someone needs to re-write MARC::Record's 'encoding' method to actually alter the encoding rather than just changing the leader
635 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
638 unless($flavour) {$flavour = C4
::Context
->preference("marcflavour")};
639 unless($to_encoding) {$to_encoding = "UTF-8"};
641 # ISO-2709 Record (MARC21 or UNIMARC)
642 if (lc($format) =~ /^marc$/o) {
643 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
644 # because MARC::Record doesn't directly provide us with an encoding method
645 # It's definitely less than idea and should be fixed eventually - kados
646 my $marcxml; # temporary storage of MARCXML scalar
647 ($error,$marcxml) = marc2marcxml
($record,$to_encoding,$flavour);
649 ($error,$newrecord) = marcxml2marc
($marcxml,$to_encoding,$flavour);
653 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
655 ($error,$marc) = marcxml2marc
($record,$to_encoding,$flavour);
657 ($error,$newrecord) = marc2marcxml
($record,$to_encoding,$flavour);
660 $error.="Unsupported record format:".$format;
662 return ($error,$newrecord);
665 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
669 my ($bibtex) = marc2bibtex($record, $id);
671 Returns a BibTex scalar
675 C<$record> - a MARC::Record object
677 C<$id> - an id for the BibTex record (might be the biblionumber)
687 my ($record, $id) = @_;
691 my $marcauthors = GetMarcAuthors
($record,C4
::Context
->preference("marcflavour"));
693 for my $authors ( map { map { @
$_ } values %$_ } @
$marcauthors ) {
694 $author .= " and " if ($author && $$authors{value
});
695 $author .= $$authors{value
} if ($$authors{value
});
698 # Defining the conversion hash according to the marcflavour
700 if (C4
::Context
->preference("marcflavour") eq "UNIMARC") {
702 # FIXME, TODO : handle repeatable fields
703 # TODO : handle more types of documents
705 # Unimarc to bibtex hash
710 title
=> $record->subfield("200", "a") || "",
711 editor
=> $record->subfield("210", "g") || "",
712 publisher
=> $record->subfield("210", "c") || "",
713 year
=> $record->subfield("210", "d") || $record->subfield("210", "h") || "",
716 volume
=> $record->subfield("200", "v") || "",
717 series
=> $record->subfield("225", "a") || "",
718 address
=> $record->subfield("210", "a") || "",
719 edition
=> $record->subfield("205", "a") || "",
720 note
=> $record->subfield("300", "a") || "",
721 url
=> $record->subfield("856", "u") || ""
725 # Marc21 to bibtex hash
730 title
=> $record->subfield("245", "a") || "",
731 editor
=> $record->subfield("260", "f") || "",
732 publisher
=> $record->subfield("260", "b") || "",
733 year
=> $record->subfield("260", "c") || $record->subfield("260", "g") || "",
736 # unimarc to marc21 specification says not to convert 200$v to marc21
737 series
=> $record->subfield("490", "a") || "",
738 address
=> $record->subfield("260", "a") || "",
739 edition
=> $record->subfield("250", "a") || "",
740 note
=> $record->subfield("500", "a") || "",
741 url
=> $record->subfield("856", "u") || ""
746 $tex .= join(",\n", $id, map { $bh{$_} ?
qq(\t$_ = "$bh{$_}") : () } keys %bh);
753 =head1 INTERNAL FUNCTIONS
755 =head2 _entity_encode - Entity-encode an array of strings
759 my ($entity_encoded_string) = _entity_encode($string);
763 my (@entity_encoded_strings) = _entity_encode(@strings);
765 Entity-encode an array of strings
773 my @strings_entity_encoded;
774 foreach my $string (@strings) {
775 my $nfc_string = NFC
($string);
776 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
777 push @strings_entity_encoded, $nfc_string;
779 return @strings_entity_encoded;
782 END { } # module clean-up code here (global destructor)
788 Joshua Ferraro <jmf@liblime.com>