3 # Copyright 2006 (C) LibLime
4 # Parts copyright 2010 BibLibre
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #use warnings; FIXME - Bug 2505
25 # please specify in which methods a given module is used
26 use MARC
::Record
; # marc2marcxml, marcxml2marc, changeEncoding
27 use MARC
::File
::XML
; # marc2marcxml, marcxml2marc, changeEncoding
28 use MARC
::Crosswalk
::DublinCore
; # marc2dcxml
29 use Biblio
::EndnoteStyle
;
30 use Unicode
::Normalize
; # _entity_encode
33 use C4
::Biblio
; #marc2bibtex
34 use C4
::Csv
; #marc2csv
35 use C4
::Koha
; #marc2csv
36 use YAML
; #marcrecords2csv
37 use Text
::CSV
::Encoded
; #marc2csv
39 use vars
qw($VERSION @ISA @EXPORT);
41 # set the version for version checking
42 $VERSION = 3.07.00.049;
46 # only export API methods
63 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
67 New in Koha 3.x. This module handles all record-related management functions.
69 =head1 API (EXPORTED FUNCTIONS)
71 =head2 marc2marc - Convert from one flavour of ISO-2709 to another
73 my ($error,$newmarc) = marc2marc($marc,$to_flavour,$from_flavour,$encoding);
75 Returns an ISO-2709 scalar
80 my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
82 if ($to_flavour =~ m/marcstd/) {
84 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
85 $marc_record_obj = $marc;
86 } else { # it's not a MARC::Record object, make it one
87 eval { $marc_record_obj = MARC
::Record
->new_from_usmarc($marc) }; # handle exceptions
89 # conversion to MARC::Record object failed, populate $error
90 if ($@
) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File
::ERROR
};
94 foreach my $field ($marc_record_obj->fields()) {
95 if ($field->tag() =~ m/9/ && ($field->tag() != '490' || C4
::Context
->preference("marcflavour") eq 'UNIMARC')) {
96 push @privatefields, $field;
97 } elsif (! ($field->is_control_field())) {
98 $field->delete_subfield(code
=> '9') if ($field->subfield('9'));
101 $marc_record_obj->delete_field($_) for @privatefields;
102 $marc = $marc_record_obj->as_usmarc();
105 $error = "Feature not yet implemented\n";
107 return ($error,$marc);
110 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
112 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
114 Returns a MARCXML scalar
116 C<$marc> - an ISO-2709 scalar or MARC::Record object
118 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
120 C<$flavour> - MARC21 or UNIMARC
122 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
127 my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
128 my $error; # the error string
129 my $marcxml; # the final MARCXML scalar
131 # test if it's already a MARC::Record object, if not, make it one
133 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
134 $marc_record_obj = $marc;
135 } else { # it's not a MARC::Record object, make it one
136 eval { $marc_record_obj = MARC
::Record
->new_from_usmarc($marc) }; # handle exceptions
138 # conversion to MARC::Record object failed, populate $error
139 if ($@
) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File
::ERROR
};
141 # only proceed if no errors so far
144 # check the record for warnings
145 my @warnings = $marc_record_obj->warnings();
147 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
148 foreach my $warn (@warnings) { warn "\t".$warn };
150 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
151 unless($flavour) {$flavour = C4
::Context
->preference("marcflavour")}; # set default MARC flavour
153 # attempt to convert the record to MARCXML
154 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
156 # record creation failed, populate $error
158 $error .= "Creation of MARCXML failed:".$MARC::File
::ERROR
;
159 $error .= "Additional information:\n";
160 my @warnings = $@
->warnings();
161 foreach my $warn (@warnings) { $error.=$warn."\n" };
163 # record creation was successful
166 # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block
167 @warnings = $marc_record_obj->warnings();
169 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
170 foreach my $warn (@warnings) { warn "\t".$warn };
174 # only proceed if no errors so far
177 # entity encode the XML unless instructed not to
178 unless ($dont_entity_encode) {
179 my ($marcxml_entity_encoded) = _entity_encode
($marcxml);
180 $marcxml = $marcxml_entity_encoded;
184 # return result to calling program
185 return ($error,$marcxml);
188 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
190 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
192 Returns an ISO-2709 scalar
194 C<$marcxml> - a MARCXML record
196 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
198 C<$flavour> - MARC21 or UNIMARC
203 my ($marcxml,$encoding,$flavour) = @_;
204 my $error; # the error string
205 my $marc; # the final ISO-2709 scalar
206 unless($encoding) {$encoding = "UTF-8"}; # set the default encoding
207 unless($flavour) {$flavour = C4
::Context
->preference("marcflavour")}; # set the default MARC flavour
209 # attempt to do the conversion
210 eval { $marc = MARC
::Record
->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
212 # record creation failed, populate $error
213 if ($@
) {$error .="\nCreation of MARCXML Record failed: ".$@
;
214 $error.=$MARC::File
::ERROR
if ($MARC::File
::ERROR
);
216 # return result to calling program
217 return ($error,$marc);
220 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
222 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
224 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
226 FIXME: should return actual XML, not just an object
228 C<$marc> - an ISO-2709 scalar or MARC::Record object
230 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
235 my ($marc,$qualified) = @_;
237 # test if it's already a MARC::Record object, if not, make it one
239 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
240 $marc_record_obj = $marc;
241 } else { # it's not a MARC::Record object, make it one
242 eval { $marc_record_obj = MARC
::Record
->new_from_usmarc($marc) }; # handle exceptions
244 # conversion to MARC::Record object failed, populate $error
246 $error .="\nCreation of MARC::Record object failed: ".$MARC::File
::ERROR
;
249 my $crosswalk = MARC
::Crosswalk
::DublinCore
->new;
251 $crosswalk = MARC
::Crosswalk
::DublinCore
->new( qualified
=> 1 );
253 my $dcxml = $crosswalk->as_dublincore($marc_record_obj);
254 my $dcxmlfinal = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
255 $dcxmlfinal .= "<metadata
256 xmlns=\"http://example.org/myapp/\"
257 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
258 xsi:schemaLocation=\"http://example.org/myapp/ http://example.org/myapp/schema.xsd\"
259 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
260 xmlns:dcterms=\"http://purl.org/dc/terms/\">";
262 foreach my $element ( $dcxml->elements() ) {
263 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name().">\n";
265 $dcxmlfinal .= "\n</metadata>";
266 return ($error,$dcxmlfinal);
269 =head2 marc2modsxml - Convert from ISO-2709 to MODS
271 my $modsxml = marc2modsxml($marc);
273 Returns a MODS scalar
279 return _transformWithStylesheet
($marc, "/prog/en/xslt/MARC21slim2MODS3-1.xsl");
282 =head2 marc2madsxml - Convert from ISO-2709 to MADS
284 my $madsxml = marc2madsxml($marc);
286 Returns a MADS scalar
292 return _transformWithStylesheet
($marc, "/prog/en/xslt/MARC21slim2MADS.xsl");
295 =head2 _transformWithStylesheet - Transform a MARC record with a stylesheet
297 my $xml = _transformWithStylesheet($marc, $stylesheet)
299 Returns the XML scalar result of the transformation. $stylesheet should
300 contain the path to a stylesheet under intrahtdocs.
304 sub _transformWithStylesheet
{
305 my ($marc, $stylesheet) = @_;
306 # grab the XML, run it through our stylesheet, push it out to the browser
307 my $xmlrecord = marc2marcxml
($marc);
308 my $xslfile = C4
::Context
->config('intrahtdocs') . $stylesheet;
309 my $parser = XML
::LibXML
->new();
310 my $xslt = XML
::LibXSLT
->new();
311 my $source = $parser->parse_string($xmlrecord);
312 my $style_doc = $parser->parse_file($xslfile);
313 my $stylesheet = $xslt->parse_stylesheet($style_doc);
314 my $results = $stylesheet->transform($source);
315 my $newxmlrecord = $stylesheet->output_string($results);
316 return ($newxmlrecord);
321 my $marc_rec_obj = MARC
::Record
->new_from_usmarc($marc);
322 my ( $abstract, $f260a, $f710a );
323 my $f260 = $marc_rec_obj->field('260');
325 $f260a = $f260->subfield('a') if $f260;
327 my $f710 = $marc_rec_obj->field('710');
329 $f710a = $f710->subfield('a');
331 my $f500 = $marc_rec_obj->field('500');
333 $abstract = $f500->subfield('a');
336 DB
=> C4
::Context
->preference("LibraryName"),
337 Title
=> $marc_rec_obj->title(),
338 Author
=> $marc_rec_obj->author(),
341 Year
=> $marc_rec_obj->publication_date,
342 Abstract
=> $abstract,
345 my $style = new Biblio
::EndnoteStyle
();
347 $template.= "DB - DB\n" if C4
::Context
->preference("LibraryName");
348 $template.="T1 - Title\n" if $marc_rec_obj->title();
349 $template.="A1 - Author\n" if $marc_rec_obj->author();
350 $template.="PB - Publisher\n" if $f710a;
351 $template.="CY - City\n" if $f260a;
352 $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
353 $template.="AB - Abstract\n" if $abstract;
354 my ($text, $errmsg) = $style->format($template, $fields);
359 =head2 marc2csv - Convert several records from UNIMARC to CSV
361 my ($csv) = marc2csv($biblios, $csvprofileid, $itemnumbers);
363 Pre and postprocessing can be done through a YAML file
367 C<$biblio> - a list of biblionumbers
369 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)
371 C<$itemnumbers> - a list of itemnumbers to export
376 my ($biblios, $id, $itemnumbers) = @_;
378 my $csv = Text
::CSV
::Encoded
->new();
381 my $configfile = "../tools/csv-profiles/$id.yaml";
382 my ($preprocess, $postprocess, $fieldprocessing);
384 ($preprocess,$postprocess, $fieldprocessing) = YAML
::LoadFile
($configfile);
388 eval $preprocess if ($preprocess);
391 if ( $itemnumbers ) {
392 for my $itemnumber ( @
$itemnumbers) {
393 my $biblionumber = GetBiblionumberFromItemnumber
$itemnumber;
394 $output .= marcrecord2csv
( $biblionumber, $id, $firstpass, $csv, $fieldprocessing, [$itemnumber] );
398 foreach my $biblio (@
$biblios) {
399 $output .= marcrecord2csv
( $biblio, $id, $firstpass, $csv, $fieldprocessing );
405 eval $postprocess if ($postprocess);
410 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
412 my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
416 C<$biblio> - a biblionumber
418 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)
420 C<$header> - true if the headers are to be printed (typically at first pass)
422 C<$csv> - an already initialised Text::CSV object
426 C<$itemnumbers> a list of itemnumbers to export
432 my ($biblio, $id, $header, $csv, $fieldprocessing, $itemnumbers) = @_;
436 my $record = GetMarcBiblio
($biblio);
438 C4
::Biblio
::EmbedItemsInMarcBiblio
( $record, $biblio, $itemnumbers );
439 # Getting the framework
440 my $frameworkcode = GetFrameworkCode
($biblio);
442 # Getting information about the csv profile
443 my $profile = GetCsvProfile
($id);
445 # Getting output encoding
446 my $encoding = $profile->{encoding
} || 'utf8';
448 my $csvseparator = $profile->{csv_separator
} || ',';
449 my $fieldseparator = $profile->{field_separator
} || '#';
450 my $subfieldseparator = $profile->{subfield_separator
} || '|';
452 # TODO: Be more generic (in case we have to handle other protected chars or more separators)
453 if ($csvseparator eq '\t') { $csvseparator = "\t" }
454 if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
455 if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
456 if ($csvseparator eq '\n') { $csvseparator = "\n" }
457 if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
458 if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
460 $csv = $csv->encoding_out($encoding) ;
461 $csv->sep_char($csvseparator);
463 # Getting the marcfields
464 my $marcfieldslist = $profile->{marcfields
};
466 # Getting the marcfields as an array
467 my @marcfieldsarray = split('\|', $marcfieldslist);
469 # Separating the marcfields from the user-supplied headers
471 foreach (@marcfieldsarray) {
472 my @result = split('=', $_);
473 if (scalar(@result) == 2) {
474 push @marcfields, { header
=> $result[0], field
=> $result[1] };
476 push @marcfields, { field
=> $result[0] }
480 # If we have to insert the headers
482 my @marcfieldsheaders;
483 my $dbh = C4
::Context
->dbh;
485 # For each field or subfield
486 foreach (@marcfields) {
488 my $field = $_->{field
};
489 # Remove any blank char that might have unintentionally insered into the tag name
492 # If we have a user-supplied header, we use it
493 if (exists $_->{header
}) {
494 push @marcfieldsheaders, $_->{header
};
496 # If not, we get the matching tag name from koha
497 if (index($field, '$') > 0) {
498 my ($fieldtag, $subfieldtag) = split('\$', $field);
499 my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
500 my $sth = $dbh->prepare($query);
501 $sth->execute($fieldtag, $subfieldtag);
502 my @results = $sth->fetchrow_array();
503 push @marcfieldsheaders, $results[0];
505 my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
506 my $sth = $dbh->prepare($query);
507 $sth->execute($field);
508 my @results = $sth->fetchrow_array();
509 push @marcfieldsheaders, $results[0];
513 $csv->combine(@marcfieldsheaders);
514 $output = $csv->string() . "\n";
517 # For each marcfield to export
519 foreach (@marcfields) {
520 my $marcfield = $_->{field
};
521 # If it is a subfield
522 if (index($marcfield, '$') > 0) {
523 my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
524 my @fields = $record->field($fieldtag);
528 foreach my $field (@fields) {
530 # We take every matching subfield
531 my @subfields = $field->subfield($subfieldtag);
532 foreach my $subfield (@subfields) {
534 # Getting authorised value
535 my $authvalues = GetKohaAuthorisedValuesFromField
($fieldtag, $subfieldtag, $frameworkcode, undef);
536 push @tmpfields, (defined $authvalues->{$subfield}) ?
$authvalues->{$subfield} : $subfield;
539 push (@fieldstab, join($subfieldseparator, @tmpfields));
542 my @fields = ($record->field($marcfield));
543 my $authvalues = GetKohaAuthorisedValuesFromField
($marcfield, undef, $frameworkcode, undef);
549 # If it is a control field
550 if ($_->is_control_field) {
551 $value = defined $authvalues->{$_->as_string} ?
$authvalues->{$_->as_string} : $_->as_string;
553 # If it is a field, we gather all subfields, joined by the subfield separator
555 my @subfields = $_->subfields;
556 foreach my $subfield (@subfields) {
557 push (@subvaluesarray, defined $authvalues->{$subfield->[1]} ?
$authvalues->{$subfield->[1]} : $subfield->[1]);
559 $value = join ($subfieldseparator, @subvaluesarray);
563 eval $fieldprocessing if ($fieldprocessing);
565 push @valuesarray, $value;
567 push (@fieldstab, join($fieldseparator, @valuesarray));
571 $csv->combine(@fieldstab);
572 $output .= $csv->string() . "\n";
579 =head2 changeEncoding - Change the encoding of a record
581 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
583 Changes the encoding of a record
585 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
587 C<$format> - MARC or MARCXML (required)
589 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
591 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
593 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)
595 FIXME: the from_encoding doesn't work yet
597 FIXME: better handling for UNIMARC, it should allow management of 100 field
599 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
604 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
607 unless($flavour) {$flavour = C4
::Context
->preference("marcflavour")};
608 unless($to_encoding) {$to_encoding = "UTF-8"};
610 # ISO-2709 Record (MARC21 or UNIMARC)
611 if (lc($format) =~ /^marc$/o) {
612 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
613 # because MARC::Record doesn't directly provide us with an encoding method
614 # It's definitely less than idea and should be fixed eventually - kados
615 my $marcxml; # temporary storage of MARCXML scalar
616 ($error,$marcxml) = marc2marcxml
($record,$to_encoding,$flavour);
618 ($error,$newrecord) = marcxml2marc
($marcxml,$to_encoding,$flavour);
622 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
624 ($error,$marc) = marcxml2marc
($record,$to_encoding,$flavour);
626 ($error,$newrecord) = marc2marcxml
($record,$to_encoding,$flavour);
629 $error.="Unsupported record format:".$format;
631 return ($error,$newrecord);
634 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
636 my ($bibtex) = marc2bibtex($record, $id);
638 Returns a BibTex scalar
640 C<$record> - a MARC::Record object
642 C<$id> - an id for the BibTex record (might be the biblionumber)
648 my ($record, $id) = @_;
650 my $marcflavour = C4
::Context
->preference("marcflavour");
655 my ( $mintag, $maxtag, $fields_filter );
656 if ( $marcflavour eq "UNIMARC" ) {
659 $fields_filter = '7..';
664 $fields_filter = '7..';
666 foreach my $field ( $record->field($fields_filter) ) {
667 next unless $field->tag() >= $mintag && $field->tag() <= $maxtag;
668 # author formatted surname, firstname
670 if ( $marcflavour eq "UNIMARC" ) {
671 $texauthor = join ', ',
672 ( $field->subfield('a'), $field->subfield('b') );
675 $texauthor = $field->subfield('a');
677 push @texauthors, $texauthor if $texauthor;
679 $author = join ' and ', @texauthors;
681 # Defining the conversion hash according to the marcflavour
683 if ( $marcflavour eq "UNIMARC" ) {
685 # FIXME, TODO : handle repeatable fields
686 # TODO : handle more types of documents
688 # Unimarc to bibtex hash
693 title
=> $record->subfield("200", "a") || "",
694 editor
=> $record->subfield("210", "g") || "",
695 publisher
=> $record->subfield("210", "c") || "",
696 year
=> $record->subfield("210", "d") || $record->subfield("210", "h") || "",
699 volume
=> $record->subfield("200", "v") || "",
700 series
=> $record->subfield("225", "a") || "",
701 address
=> $record->subfield("210", "a") || "",
702 edition
=> $record->subfield("205", "a") || "",
703 note
=> $record->subfield("300", "a") || "",
704 url
=> $record->subfield("856", "u") || ""
708 # Marc21 to bibtex hash
713 title
=> $record->subfield("245", "a") || "",
714 editor
=> $record->subfield("260", "f") || "",
715 publisher
=> $record->subfield("260", "b") || "",
716 year
=> $record->subfield("260", "c") || $record->subfield("260", "g") || "",
719 # unimarc to marc21 specification says not to convert 200$v to marc21
720 series
=> $record->subfield("490", "a") || "",
721 address
=> $record->subfield("260", "a") || "",
722 edition
=> $record->subfield("250", "a") || "",
723 note
=> $record->subfield("500", "a") || "",
724 url
=> $record->subfield("856", "u") || ""
729 $tex .= join(",\n", $id, map { $bh{$_} ?
qq(\t$_ = "$bh{$_}") : () } keys %bh);
736 =head1 INTERNAL FUNCTIONS
738 =head2 _entity_encode - Entity-encode an array of strings
740 my ($entity_encoded_string) = _entity_encode($string);
744 my (@entity_encoded_strings) = _entity_encode(@strings);
746 Entity-encode an array of strings
752 my @strings_entity_encoded;
753 foreach my $string (@strings) {
754 my $nfc_string = NFC
($string);
755 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
756 push @strings_entity_encoded, $nfc_string;
758 return @strings_entity_encoded;
761 END { } # module clean-up code here (global destructor)
767 Joshua Ferraro <jmf@liblime.com>