Translation updates for Koha 3.22.0 release
[koha.git] / C4 / Record.pm
blobf46651bea708baaa212e71a833526ad8fd944f7d
1 package C4::Record;
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
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 use strict;
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
31 use C4::Biblio; #marc2bibtex
32 use C4::Csv; #marc2csv
33 use C4::Koha; #marc2csv
34 use C4::XSLT ();
35 use YAML; #marcrecords2csv
36 use Template;
37 use Text::CSV::Encoded; #marc2csv
38 use Koha::SimpleMARC qw(read_field);
40 use vars qw($VERSION @ISA @EXPORT);
42 # set the version for version checking
43 $VERSION = 3.07.00.049;
45 @ISA = qw(Exporter);
47 # only export API methods
49 @EXPORT = qw(
50 &marc2endnote
51 &marc2marc
52 &marc2marcxml
53 &marcxml2marc
54 &marc2dcxml
55 &marc2modsxml
56 &marc2madsxml
57 &marc2bibtex
58 &marc2csv
59 &changeEncoding
62 =head1 NAME
64 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
66 =head1 SYNOPSIS
68 New in Koha 3.x. This module handles all record-related management functions.
70 =head1 API (EXPORTED FUNCTIONS)
72 =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
78 =cut
80 sub marc2marc {
81 my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
82 my $error;
83 if ($to_flavour =~ m/marcstd/) {
84 my $marc_record_obj;
85 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
86 $marc_record_obj = $marc;
87 } else { # it's not a MARC::Record object, make it one
88 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
90 # conversion to MARC::Record object failed, populate $error
91 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
93 unless ($error) {
94 my @privatefields;
95 foreach my $field ($marc_record_obj->fields()) {
96 if ($field->tag() =~ m/9/ && ($field->tag() != '490' || C4::Context->preference("marcflavour") eq 'UNIMARC')) {
97 push @privatefields, $field;
98 } elsif (! ($field->is_control_field())) {
99 $field->delete_subfield(code => '9') if ($field->subfield('9'));
102 $marc_record_obj->delete_field($_) for @privatefields;
103 $marc = $marc_record_obj->as_usmarc();
105 } else {
106 $error = "Feature not yet implemented\n";
108 return ($error,$marc);
111 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
113 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
115 Returns a MARCXML scalar
117 C<$marc> - an ISO-2709 scalar or MARC::Record object
119 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
121 C<$flavour> - MARC21 or UNIMARC
123 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
125 =cut
127 sub marc2marcxml {
128 my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
129 my $error; # the error string
130 my $marcxml; # the final MARCXML scalar
132 # test if it's already a MARC::Record object, if not, make it one
133 my $marc_record_obj;
134 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
135 $marc_record_obj = $marc;
136 } else { # it's not a MARC::Record object, make it one
137 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
139 # conversion to MARC::Record object failed, populate $error
140 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
142 # only proceed if no errors so far
143 unless ($error) {
145 # check the record for warnings
146 my @warnings = $marc_record_obj->warnings();
147 if (@warnings) {
148 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
149 foreach my $warn (@warnings) { warn "\t".$warn };
151 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
152 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour
154 # attempt to convert the record to MARCXML
155 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
157 # record creation failed, populate $error
158 if ($@) {
159 $error .= "Creation of MARCXML failed:".$MARC::File::ERROR;
160 $error .= "Additional information:\n";
161 my @warnings = $@->warnings();
162 foreach my $warn (@warnings) { $error.=$warn."\n" };
164 # record creation was successful
165 } else {
167 # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block
168 @warnings = $marc_record_obj->warnings();
169 if (@warnings) {
170 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
171 foreach my $warn (@warnings) { warn "\t".$warn };
175 # only proceed if no errors so far
176 unless ($error) {
178 # entity encode the XML unless instructed not to
179 unless ($dont_entity_encode) {
180 my ($marcxml_entity_encoded) = _entity_encode($marcxml);
181 $marcxml = $marcxml_entity_encoded;
185 # return result to calling program
186 return ($error,$marcxml);
189 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
191 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
193 Returns an ISO-2709 scalar
195 C<$marcxml> - a MARCXML record
197 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
199 C<$flavour> - MARC21 or UNIMARC
201 =cut
203 sub marcxml2marc {
204 my ($marcxml,$encoding,$flavour) = @_;
205 my $error; # the error string
206 my $marc; # the final ISO-2709 scalar
207 unless($encoding) {$encoding = "UTF-8"}; # set the default encoding
208 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set the default MARC flavour
210 # attempt to do the conversion
211 eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
213 # record creation failed, populate $error
214 if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@;
215 $error.=$MARC::File::ERROR if ($MARC::File::ERROR);
217 # return result to calling program
218 return ($error,$marc);
221 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
223 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
225 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
227 FIXME: should return actual XML, not just an object
229 C<$marc> - an ISO-2709 scalar or MARC::Record object
231 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
233 =cut
235 sub marc2dcxml {
236 my ($marc,$qualified) = @_;
237 my $error;
238 # test if it's already a MARC::Record object, if not, make it one
239 my $marc_record_obj;
240 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
241 $marc_record_obj = $marc;
242 } else { # it's not a MARC::Record object, make it one
243 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
245 # conversion to MARC::Record object failed, populate $error
246 if ($@) {
247 $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR;
250 my $crosswalk = MARC::Crosswalk::DublinCore->new;
251 if ($qualified) {
252 $crosswalk = MARC::Crosswalk::DublinCore->new( qualified => 1 );
254 my $dcxml = $crosswalk->as_dublincore($marc_record_obj);
255 my $dcxmlfinal = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
256 $dcxmlfinal .= "<metadata
257 xmlns=\"http://example.org/myapp/\"
258 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
259 xsi:schemaLocation=\"http://example.org/myapp/ http://example.org/myapp/schema.xsd\"
260 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
261 xmlns:dcterms=\"http://purl.org/dc/terms/\">";
263 foreach my $element ( $dcxml->elements() ) {
264 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name().">\n";
266 $dcxmlfinal .= "\n</metadata>";
267 return ($error,$dcxmlfinal);
270 =head2 marc2modsxml - Convert from ISO-2709 to MODS
272 my $modsxml = marc2modsxml($marc);
274 Returns a MODS scalar
276 =cut
278 sub marc2modsxml {
279 my ($marc) = @_;
280 return _transformWithStylesheet($marc, "/prog/en/xslt/MARC21slim2MODS3-1.xsl");
283 =head2 marc2madsxml - Convert from ISO-2709 to MADS
285 my $madsxml = marc2madsxml($marc);
287 Returns a MADS scalar
289 =cut
291 sub marc2madsxml {
292 my ($marc) = @_;
293 return _transformWithStylesheet($marc, "/prog/en/xslt/MARC21slim2MADS.xsl");
296 =head2 _transformWithStylesheet - Transform a MARC record with a stylesheet
298 my $xml = _transformWithStylesheet($marc, $stylesheet)
300 Returns the XML scalar result of the transformation. $stylesheet should
301 contain the path to a stylesheet under intrahtdocs.
303 =cut
305 sub _transformWithStylesheet {
306 my ($marc, $stylesheet) = @_;
307 # grab the XML, run it through our stylesheet, push it out to the browser
308 my $xmlrecord = marc2marcxml($marc);
309 my $xslfile = C4::Context->config('intrahtdocs') . $stylesheet;
310 return C4::XSLT::engine->transform($xmlrecord, $xslfile);
313 sub marc2endnote {
314 my ($marc) = @_;
315 my $marc_rec_obj = MARC::Record->new_from_usmarc($marc);
316 my ( $abstract, $f260a, $f710a );
317 my $f260 = $marc_rec_obj->field('260');
318 if ($f260) {
319 $f260a = $f260->subfield('a') if $f260;
321 my $f710 = $marc_rec_obj->field('710');
322 if ($f710) {
323 $f710a = $f710->subfield('a');
325 my $f500 = $marc_rec_obj->field('500');
326 if ($f500) {
327 $abstract = $f500->subfield('a');
329 my $fields = {
330 DB => C4::Context->preference("LibraryName"),
331 Title => $marc_rec_obj->title(),
332 Author => $marc_rec_obj->author(),
333 Publisher => $f710a,
334 City => $f260a,
335 Year => $marc_rec_obj->publication_date,
336 Abstract => $abstract,
338 my $endnote;
339 my $style = new Biblio::EndnoteStyle();
340 my $template;
341 $template.= "DB - DB\n" if C4::Context->preference("LibraryName");
342 $template.="T1 - Title\n" if $marc_rec_obj->title();
343 $template.="A1 - Author\n" if $marc_rec_obj->author();
344 $template.="PB - Publisher\n" if $f710a;
345 $template.="CY - City\n" if $f260a;
346 $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
347 $template.="AB - Abstract\n" if $abstract;
348 my ($text, $errmsg) = $style->format($template, $fields);
349 return ($text);
353 =head2 marc2csv - Convert several records from UNIMARC to CSV
355 my ($csv) = marc2csv($biblios, $csvprofileid, $itemnumbers);
357 Pre and postprocessing can be done through a YAML file
359 Returns a CSV scalar
361 C<$biblio> - a list of biblionumbers
363 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)
365 C<$itemnumbers> - a list of itemnumbers to export
367 =cut
369 sub marc2csv {
370 my ($biblios, $id, $itemnumbers) = @_;
371 $itemnumbers ||= [];
372 my $output;
373 my $csv = Text::CSV::Encoded->new();
375 # Getting yaml file
376 my $configfile = "../tools/csv-profiles/$id.yaml";
377 my ($preprocess, $postprocess, $fieldprocessing);
378 if (-e $configfile){
379 ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
382 # Preprocessing
383 eval $preprocess if ($preprocess);
385 my $firstpass = 1;
386 if ( @$itemnumbers ) {
387 for my $itemnumber ( @$itemnumbers) {
388 my $biblionumber = GetBiblionumberFromItemnumber $itemnumber;
389 $output .= marcrecord2csv( $biblionumber, $id, $firstpass, $csv, $fieldprocessing, [$itemnumber] );
390 $firstpass = 0;
392 } else {
393 foreach my $biblio (@$biblios) {
394 $output .= marcrecord2csv( $biblio, $id, $firstpass, $csv, $fieldprocessing );
395 $firstpass = 0;
399 # Postprocessing
400 eval $postprocess if ($postprocess);
402 return $output;
405 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
407 my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
409 Returns a CSV scalar
411 C<$biblio> - a biblionumber
413 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)
415 C<$header> - true if the headers are to be printed (typically at first pass)
417 C<$csv> - an already initialised Text::CSV object
419 C<$fieldprocessing>
421 C<$itemnumbers> a list of itemnumbers to export
423 =cut
425 sub marcrecord2csv {
426 my ($biblio, $id, $header, $csv, $fieldprocessing, $itemnumbers) = @_;
427 my $output;
429 # Getting the record
430 my $record = GetMarcBiblio($biblio);
431 return unless $record;
432 C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblio, $itemnumbers );
433 # Getting the framework
434 my $frameworkcode = GetFrameworkCode($biblio);
436 # Getting information about the csv profile
437 my $profile = GetCsvProfile($id);
439 # Getting output encoding
440 my $encoding = $profile->{encoding} || 'utf8';
441 # Getting separators
442 my $csvseparator = $profile->{csv_separator} || ',';
443 my $fieldseparator = $profile->{field_separator} || '#';
444 my $subfieldseparator = $profile->{subfield_separator} || '|';
446 # TODO: Be more generic (in case we have to handle other protected chars or more separators)
447 if ($csvseparator eq '\t') { $csvseparator = "\t" }
448 if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
449 if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
450 if ($csvseparator eq '\n') { $csvseparator = "\n" }
451 if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
452 if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
454 $csv = $csv->encoding_out($encoding) ;
455 $csv->sep_char($csvseparator);
457 # Getting the marcfields
458 my $marcfieldslist = $profile->{content};
460 # Getting the marcfields as an array
461 my @marcfieldsarray = split('\|', $marcfieldslist);
463 # Separating the marcfields from the user-supplied headers
464 my @csv_structures;
465 foreach (@marcfieldsarray) {
466 my @result = split('=', $_, 2);
467 my $content = ( @result == 2 )
468 ? $result[1]
469 : $result[0];
470 my @fields;
471 while ( $content =~ m|(\d{3})\$?(.)?|g ) {
472 my $fieldtag = $1;
473 my $subfieldtag = $2 || undef;
474 push @fields, { fieldtag => $fieldtag, subfieldtag => $subfieldtag };
476 if ( @result == 2) {
477 push @csv_structures, { header => $result[0], content => $content, fields => \@fields };
478 } else {
479 push @csv_structures, { content => $content, fields => \@fields }
483 my ( @marcfieldsheaders, @csv_rows );
484 my $dbh = C4::Context->dbh;
486 my $field_list;
487 for my $field ( $record->fields ) {
488 my $fieldtag = $field->tag;
489 my $values;
490 if ( $field->is_control_field ) {
491 $values = $field->data();
492 } else {
493 $values->{indicator}{1} = $field->indicator(1);
494 $values->{indicator}{2} = $field->indicator(2);
495 for my $subfield ( $field->subfields ) {
496 my $subfieldtag = $subfield->[0];
497 my $value = $subfield->[1];
498 push @{ $values->{$subfieldtag} }, $value;
501 # We force the key as an integer (trick for 00X and OXX fields)
502 push @{ $field_list->{fields}{0+$fieldtag} }, $values;
505 # For each field or subfield
506 foreach my $csv_structure (@csv_structures) {
507 my @field_values;
508 my $tags = $csv_structure->{fields};
509 my $content = $csv_structure->{content};
511 if ( $header ) {
512 # If we have a user-supplied header, we use it
513 if ( exists $csv_structure->{header} ) {
514 push @marcfieldsheaders, $csv_structure->{header};
515 } else {
516 # If not, we get the matching tag name from koha
517 my $tag = $tags->[0];
518 if ( $tag->{subfieldtag} ) {
519 my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
520 my @results = $dbh->selectrow_array( $query, {}, $tag->{fieldtag}, $tag->{subfieldtag} );
521 push @marcfieldsheaders, $results[0];
522 } else {
523 my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
524 my @results = $dbh->selectrow_array( $query, {}, $tag->{fieldtag} );
525 push @marcfieldsheaders, $results[0];
530 # TT tags exist
531 if ( $content =~ m|\[\%.*\%\]| ) {
532 my $tt = Template->new();
533 my $template = $content;
534 my $vars;
535 # Replace 00X and 0XX with X or XX
536 $content =~ s|fields.00(\d)|fields.$1|g;
537 $content =~ s|fields.0(\d{2})|fields.$1|g;
538 my $tt_output;
539 $tt->process( \$content, $field_list, \$tt_output );
540 push @csv_rows, $tt_output;
541 } else {
542 for my $tag ( @$tags ) {
543 my @fields = $record->field( $tag->{fieldtag} );
544 # If it is a subfield
545 my @loop_values;
546 if ( $tag->{subfieldtag} ) {
547 # For each field
548 foreach my $field (@fields) {
549 my @subfields = $field->subfield( $tag->{subfieldtag} );
550 foreach my $subfield (@subfields) {
551 my $authvalues = GetKohaAuthorisedValuesFromField( $tag->{fieldtag}, $tag->{subfieldtag}, $frameworkcode, undef);
552 push @loop_values, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
556 # Or a field
557 } else {
558 my $authvalues = GetKohaAuthorisedValuesFromField( $tag->{fieldtag}, undef, $frameworkcode, undef);
560 foreach my $field ( @fields ) {
561 my $value;
563 # If it is a control field
564 if ($field->is_control_field) {
565 $value = defined $authvalues->{$field->as_string} ? $authvalues->{$field->as_string} : $field->as_string;
566 } else {
567 # If it is a field, we gather all subfields, joined by the subfield separator
568 my @subvaluesarray;
569 my @subfields = $field->subfields;
570 foreach my $subfield (@subfields) {
571 push (@subvaluesarray, defined $authvalues->{$subfield->[1]} ? $authvalues->{$subfield->[1]} : $subfield->[1]);
573 $value = join ($subfieldseparator, @subvaluesarray);
576 # Field processing
577 my $marcfield = $tag->{fieldtag}; # This line fixes a retrocompatibility concern
578 # The "processing" could be based on the $marcfield variable.
579 eval $fieldprocessing if ($fieldprocessing);
581 push @loop_values, $value;
585 push @field_values, {
586 fieldtag => $tag->{fieldtag},
587 subfieldtag => $tag->{subfieldtag},
588 values => \@loop_values,
591 for my $field_value ( @field_values ) {
592 if ( $field_value->{subfieldtag} ) {
593 push @csv_rows, join( $subfieldseparator, @{ $field_value->{values} } );
594 } else {
595 push @csv_rows, join( $fieldseparator, @{ $field_value->{values} } );
602 if ( $header ) {
603 $csv->combine(@marcfieldsheaders);
604 $output = $csv->string() . "\n";
606 $csv->combine(@csv_rows);
607 $output .= $csv->string() . "\n";
609 return $output;
614 =head2 changeEncoding - Change the encoding of a record
616 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
618 Changes the encoding of a record
620 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
622 C<$format> - MARC or MARCXML (required)
624 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
626 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
628 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)
630 FIXME: the from_encoding doesn't work yet
632 FIXME: better handling for UNIMARC, it should allow management of 100 field
634 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
636 =cut
638 sub changeEncoding {
639 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
640 my $newrecord;
641 my $error;
642 unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
643 unless($to_encoding) {$to_encoding = "UTF-8"};
645 # ISO-2709 Record (MARC21 or UNIMARC)
646 if (lc($format) =~ /^marc$/o) {
647 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
648 # because MARC::Record doesn't directly provide us with an encoding method
649 # It's definitely less than idea and should be fixed eventually - kados
650 my $marcxml; # temporary storage of MARCXML scalar
651 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
652 unless ($error) {
653 ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
656 # MARCXML Record
657 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
658 my $marc;
659 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
660 unless ($error) {
661 ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
663 } else {
664 $error.="Unsupported record format:".$format;
666 return ($error,$newrecord);
669 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
671 my ($bibtex) = marc2bibtex($record, $id);
673 Returns a BibTex scalar
675 C<$record> - a MARC::Record object
677 C<$id> - an id for the BibTex record (might be the biblionumber)
679 =cut
682 sub marc2bibtex {
683 my ($record, $id) = @_;
684 my $tex;
685 my $marcflavour = C4::Context->preference("marcflavour");
687 # Authors
688 my $author;
689 my @texauthors;
690 my @authorFields = ('100','110','111','700','710','711');
691 @authorFields = ('700','701','702','710','711','721') if ( $marcflavour eq "UNIMARC" );
693 foreach my $field ( @authorFields ) {
694 # author formatted surname, firstname
695 my $texauthor = '';
696 if ( $marcflavour eq "UNIMARC" ) {
697 $texauthor = join ', ',
698 ( $record->subfield($field,"a"), $record->subfield($field,"b") );
699 } else {
700 $texauthor = $record->subfield($field,"a");
702 push @texauthors, $texauthor if $texauthor;
704 $author = join ' and ', @texauthors;
706 # Defining the conversion array according to the marcflavour
707 my @bh;
708 if ( $marcflavour eq "UNIMARC" ) {
710 # FIXME, TODO : handle repeatable fields
711 # TODO : handle more types of documents
713 # Unimarc to bibtex array
714 @bh = (
716 # Mandatory
717 author => $author,
718 title => $record->subfield("200", "a") || "",
719 editor => $record->subfield("210", "g") || "",
720 publisher => $record->subfield("210", "c") || "",
721 year => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
723 # Optional
724 volume => $record->subfield("200", "v") || "",
725 series => $record->subfield("225", "a") || "",
726 address => $record->subfield("210", "a") || "",
727 edition => $record->subfield("205", "a") || "",
728 note => $record->subfield("300", "a") || "",
729 url => $record->subfield("856", "u") || ""
731 } else {
733 # Marc21 to bibtex array
734 @bh = (
736 # Mandatory
737 author => $author,
738 title => $record->subfield("245", "a") || "",
739 editor => $record->subfield("260", "f") || "",
740 publisher => $record->subfield("264", "b") || $record->subfield("260", "b") || "",
741 year => $record->subfield("264", "c") || $record->subfield("260", "c") || $record->subfield("260", "g") || "",
743 # Optional
744 # unimarc to marc21 specification says not to convert 200$v to marc21
745 series => $record->subfield("490", "a") || "",
746 address => $record->subfield("264", "a") || $record->subfield("260", "a") || "",
747 edition => $record->subfield("250", "a") || "",
748 note => $record->subfield("500", "a") || "",
749 url => $record->subfield("856", "u") || ""
753 my $BibtexExportAdditionalFields = C4::Context->preference('BibtexExportAdditionalFields');
754 my $additional_fields;
755 if ($BibtexExportAdditionalFields) {
756 $BibtexExportAdditionalFields = "$BibtexExportAdditionalFields\n\n";
757 $additional_fields = eval { YAML::Load($BibtexExportAdditionalFields); };
758 if ($@) {
759 warn "Unable to parse BibtexExportAdditionalFields : $@";
760 $additional_fields = undef;
764 if ( $additional_fields && $additional_fields->{'@'} ) {
765 my ( $f, $sf ) = split( /\$/, $additional_fields->{'@'} );
766 my ( $type ) = read_field( { record => $record, field => $f, subfield => $sf, field_numbers => [1] } );
768 if ($type) {
769 $tex .= '@' . $type . '{';
771 else {
772 $tex .= "\@book{";
775 else {
776 $tex .= "\@book{";
779 my @elt;
780 for ( my $i = 0 ; $i < scalar( @bh ) ; $i = $i + 2 ) {
781 next unless $bh[$i+1];
782 push @elt, qq|\t$bh[$i] = {$bh[$i+1]}|;
784 $tex .= join(",\n", $id, @elt);
786 if ($additional_fields) {
787 $tex .= ",\n";
788 foreach my $bibtex_tag ( keys %$additional_fields ) {
789 next if $bibtex_tag eq '@';
791 my @fields =
792 ref( $additional_fields->{$bibtex_tag} ) eq 'ARRAY'
793 ? @{ $additional_fields->{$bibtex_tag} }
794 : $additional_fields->{$bibtex_tag};
796 for my $tag (@fields) {
797 my ( $f, $sf ) = split( /\$/, $tag );
798 my @values = read_field( { record => $record, field => $f, subfield => $sf } );
799 foreach my $v (@values) {
800 $tex .= qq(\t$bibtex_tag = {$v}\n);
805 else {
806 $tex .= "\n";
809 $tex .= "}\n";
811 return $tex;
815 =head1 INTERNAL FUNCTIONS
817 =head2 _entity_encode - Entity-encode an array of strings
819 my ($entity_encoded_string) = _entity_encode($string);
823 my (@entity_encoded_strings) = _entity_encode(@strings);
825 Entity-encode an array of strings
827 =cut
829 sub _entity_encode {
830 my @strings = @_;
831 my @strings_entity_encoded;
832 foreach my $string (@strings) {
833 my $nfc_string = NFC($string);
834 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
835 push @strings_entity_encoded, $nfc_string;
837 return @strings_entity_encoded;
840 END { } # module clean-up code here (global destructor)
842 __END__
844 =head1 AUTHOR
846 Joshua Ferraro <jmf@liblime.com>
848 =head1 MODIFICATIONS
851 =cut