Merge remote-tracking branch 'jcamins/bug_8281_qa'
[koha.git] / C4 / Record.pm
1 package C4::Record;
2 #
3 # Copyright 2006 (C) LibLime
4 # Parts copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
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
11 # version.
12 #
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.
16 #
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.
20 #
21 #
22 use strict;
23 #use warnings; FIXME - Bug 2505
24
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 XML::LibXSLT;
32 use XML::LibXML;
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
38
39 use vars qw($VERSION @ISA @EXPORT);
40
41 # set the version for version checking
42 $VERSION = 3.07.00.049;
43
44 @ISA = qw(Exporter);
45
46 # only export API methods
47
48 @EXPORT = qw(
49   &marc2endnote
50   &marc2marc
51   &marc2marcxml
52   &marcxml2marc
53   &marc2dcxml
54   &marc2modsxml
55   &marc2madsxml
56   &marc2bibtex
57   &marc2csv
58   &changeEncoding
59 );
60
61 =head1 NAME
62
63 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
64
65 =head1 SYNOPSIS
66
67 New in Koha 3.x. This module handles all record-related management functions.
68
69 =head1 API (EXPORTED FUNCTIONS)
70
71 =head2 marc2marc - Convert from one flavour of ISO-2709 to another
72
73   my ($error,$newmarc) = marc2marc($marc,$to_flavour,$from_flavour,$encoding);
74
75 Returns an ISO-2709 scalar
76
77 =cut
78
79 sub marc2marc {
80         my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
81         my $error;
82     if ($to_flavour =~ m/marcstd/) {
83         my $marc_record_obj;
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
88
89 # conversion to MARC::Record object failed, populate $error
90                 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
91         }
92         unless ($error) {
93             my @privatefields;
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'));
99                 }
100             }
101             $marc_record_obj->delete_field($_) for @privatefields;
102             $marc = $marc_record_obj->as_usmarc();
103         }
104     } else {
105         $error = "Feature not yet implemented\n";
106     }
107         return ($error,$marc);
108 }
109
110 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
111
112   my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
113
114 Returns a MARCXML scalar
115
116 C<$marc> - an ISO-2709 scalar or MARC::Record object
117
118 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
119
120 C<$flavour> - MARC21 or UNIMARC
121
122 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
123
124 =cut
125
126 sub marc2marcxml {
127         my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
128         my $error; # the error string
129         my $marcxml; # the final MARCXML scalar
130
131         # test if it's already a MARC::Record object, if not, make it one
132         my $marc_record_obj;
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
137
138                 # conversion to MARC::Record object failed, populate $error
139                 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
140         }
141         # only proceed if no errors so far
142         unless ($error) {
143
144                 # check the record for warnings
145                 my @warnings = $marc_record_obj->warnings();
146                 if (@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 };
149                 }
150                 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
151                 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour
152
153                 # attempt to convert the record to MARCXML
154                 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
155
156                 # record creation failed, populate $error
157                 if ($@) {
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" };
162
163                 # record creation was successful
164         } else {
165
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();
168                         if (@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 };
171                         }
172                 }
173
174                 # only proceed if no errors so far
175                 unless ($error) {
176
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;
181                 }
182                 }
183         }
184         # return result to calling program
185         return ($error,$marcxml);
186 }
187
188 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
189
190   my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
191
192 Returns an ISO-2709 scalar
193
194 C<$marcxml> - a MARCXML record
195
196 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
197
198 C<$flavour> - MARC21 or UNIMARC
199
200 =cut
201
202 sub marcxml2marc {
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
208
209         # attempt to do the conversion
210         eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
211
212         # record creation failed, populate $error
213         if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@;
214                 $error.=$MARC::File::ERROR if ($MARC::File::ERROR);
215                 };
216         # return result to calling program
217         return ($error,$marc);
218 }
219
220 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
221
222   my ($error,$dcxml) = marc2dcxml($marc,$qualified);
223
224 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
225
226 FIXME: should return actual XML, not just an object
227
228 C<$marc> - an ISO-2709 scalar or MARC::Record object
229
230 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
231
232 =cut
233
234 sub marc2dcxml {
235         my ($marc,$qualified) = @_;
236         my $error;
237     # test if it's already a MARC::Record object, if not, make it one
238     my $marc_record_obj;
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
243
244                 # conversion to MARC::Record object failed, populate $error
245                 if ($@) {
246                         $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR;
247                 }
248         }
249         my $crosswalk = MARC::Crosswalk::DublinCore->new;
250         if ($qualified) {
251                 $crosswalk = MARC::Crosswalk::DublinCore->new( qualified => 1 );
252         }
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/\">";
261
262         foreach my $element ( $dcxml->elements() ) {
263                 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name().">\n";
264     }
265         $dcxmlfinal .= "\n</metadata>";
266         return ($error,$dcxmlfinal);
267 }
268
269 =head2 marc2modsxml - Convert from ISO-2709 to MODS
270
271   my $modsxml = marc2modsxml($marc);
272
273 Returns a MODS scalar
274
275 =cut
276
277 sub marc2modsxml {
278     my ($marc) = @_;
279     return _transformWithStylesheet($marc, "/prog/en/xslt/MARC21slim2MODS3-1.xsl");
280 }
281
282 =head2 marc2madsxml - Convert from ISO-2709 to MADS
283
284   my $madsxml = marc2madsxml($marc);
285
286 Returns a MADS scalar
287
288 =cut
289
290 sub marc2madsxml {
291     my ($marc) = @_;
292     return _transformWithStylesheet($marc, "/prog/en/xslt/MARC21slim2MADS.xsl");
293 }
294
295 =head2 _transformWithStylesheet - Transform a MARC record with a stylesheet
296
297     my $xml = _transformWithStylesheet($marc, $stylesheet)
298
299 Returns the XML scalar result of the transformation. $stylesheet should
300 contain the path to a stylesheet under intrahtdocs.
301
302 =cut
303
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);
317 }
318
319 sub marc2endnote {
320     my ($marc) = @_;
321         my $marc_rec_obj =  MARC::Record->new_from_usmarc($marc);
322     my ( $abstract, $f260a, $f710a );
323     my $f260 = $marc_rec_obj->field('260');
324     if ($f260) {
325         $f260a = $f260->subfield('a') if $f260;
326     }
327     my $f710 = $marc_rec_obj->field('710');
328     if ($f710) {
329         $f710a = $f710->subfield('a');
330     }
331     my $f500 = $marc_rec_obj->field('500');
332     if ($f500) {
333         $abstract = $f500->subfield('a');
334     }
335         my $fields = {
336                 DB => C4::Context->preference("LibraryName"),
337                 Title => $marc_rec_obj->title(),        
338                 Author => $marc_rec_obj->author(),      
339                 Publisher => $f710a,
340                 City => $f260a,
341                 Year => $marc_rec_obj->publication_date,
342                 Abstract => $abstract,
343         };
344         my $endnote;
345         my $style = new Biblio::EndnoteStyle();
346         my $template;
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);
355         return ($text);
356         
357 }
358
359 =head2 marc2csv - Convert several records from UNIMARC to CSV
360
361   my ($csv) = marc2csv($biblios, $csvprofileid);
362
363 Pre and postprocessing can be done through a YAML file
364
365 Returns a CSV scalar
366
367 C<$biblio> - a list of biblionumbers
368
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)
370
371 =cut
372
373 sub marc2csv {
374     my ($biblios, $id) = @_;
375     my $output;
376     my $csv = Text::CSV::Encoded->new();
377
378     # Getting yaml file
379     my $configfile = "../tools/csv-profiles/$id.yaml";
380     my ($preprocess, $postprocess, $fieldprocessing);
381     if (-e $configfile){
382         ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
383     }
384
385     # Preprocessing
386     eval $preprocess if ($preprocess);
387
388     my $firstpass = 1;
389     foreach my $biblio (@$biblios) {
390         $output .= marcrecord2csv($biblio, $id, $firstpass, $csv, $fieldprocessing) ;
391         $firstpass = 0;
392     }
393
394     # Postprocessing
395     eval $postprocess if ($postprocess);
396
397     return $output;
398 }
399
400 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
401
402   my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
403
404 Returns a CSV scalar
405
406 C<$biblio> - a biblionumber
407
408 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)
409
410 C<$header> - true if the headers are to be printed (typically at first pass)
411
412 C<$csv> - an already initialised Text::CSV object
413
414 =cut
415
416
417 sub marcrecord2csv {
418     my ($biblio, $id, $header, $csv, $fieldprocessing) = @_;
419     my $output;
420
421     # Getting the record
422     my $record = GetMarcBiblio($biblio, 1);
423     next unless $record;
424     # Getting the framework
425     my $frameworkcode = GetFrameworkCode($biblio);
426
427     # Getting information about the csv profile
428     my $profile = GetCsvProfile($id);
429
430     # Getting output encoding
431     my $encoding          = $profile->{encoding} || 'utf8';
432     # Getting separators
433     my $csvseparator      = $profile->{csv_separator}      || ',';
434     my $fieldseparator    = $profile->{field_separator}    || '#';
435     my $subfieldseparator = $profile->{subfield_separator} || '|';
436
437     # TODO: Be more generic (in case we have to handle other protected chars or more separators)
438     if ($csvseparator eq '\t') { $csvseparator = "\t" }
439     if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
440     if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
441     if ($csvseparator eq '\n') { $csvseparator = "\n" }
442     if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
443     if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
444
445     $csv = $csv->encoding_out($encoding) ;
446     $csv->sep_char($csvseparator);
447
448     # Getting the marcfields
449     my $marcfieldslist = $profile->{marcfields};
450
451     # Getting the marcfields as an array
452     my @marcfieldsarray = split('\|', $marcfieldslist);
453
454    # Separating the marcfields from the user-supplied headers
455     my @marcfields;
456     foreach (@marcfieldsarray) {
457         my @result = split('=', $_);
458         if (scalar(@result) == 2) {
459            push @marcfields, { header => $result[0], field => $result[1] }; 
460         } else {
461            push @marcfields, { field => $result[0] }
462         }
463     }
464
465     # If we have to insert the headers
466     if ($header) {
467         my @marcfieldsheaders;
468         my $dbh   = C4::Context->dbh;
469
470         # For each field or subfield
471         foreach (@marcfields) {
472
473             my $field = $_->{field};
474         # Remove any blank char that might have unintentionally insered into the tag name
475         $field =~ s/\s+//g; 
476
477             # If we have a user-supplied header, we use it
478             if (exists $_->{header}) {
479                     push @marcfieldsheaders, $_->{header};
480             } else {
481                 # If not, we get the matching tag name from koha
482                 if (index($field, '$') > 0) {
483                     my ($fieldtag, $subfieldtag) = split('\$', $field);
484                     my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
485                     my $sth = $dbh->prepare($query);
486                     $sth->execute($fieldtag, $subfieldtag);
487                     my @results = $sth->fetchrow_array();
488                     push @marcfieldsheaders, $results[0];
489                 } else {
490                     my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
491                     my $sth = $dbh->prepare($query);
492                     $sth->execute($field);
493                     my @results = $sth->fetchrow_array();
494                     push @marcfieldsheaders, $results[0];
495                 }
496             }
497         }
498         $csv->combine(@marcfieldsheaders);
499         $output = $csv->string() . "\n";        
500     }
501
502     # For each marcfield to export
503     my @fieldstab;
504     foreach (@marcfields) {
505         my $marcfield = $_->{field};
506         # If it is a subfield
507         if (index($marcfield, '$') > 0) {
508             my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
509             my @fields = $record->field($fieldtag);
510             my @tmpfields;
511
512             # For each field
513             foreach my $field (@fields) {
514
515                 # We take every matching subfield
516                 my @subfields = $field->subfield($subfieldtag);
517                 foreach my $subfield (@subfields) {
518
519                     # Getting authorised value
520                     my $authvalues = GetKohaAuthorisedValuesFromField($fieldtag, $subfieldtag, $frameworkcode, undef);
521                     push @tmpfields, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
522                 }
523             }
524             push (@fieldstab, join($subfieldseparator, @tmpfields));            
525         # Or a field
526         } else {
527             my @fields = ($record->field($marcfield));
528             my $authvalues = GetKohaAuthorisedValuesFromField($marcfield, undef, $frameworkcode, undef);
529
530             my @valuesarray;
531             foreach (@fields) {
532                 my $value;
533
534                 # Getting authorised value
535                 $value = defined $authvalues->{$_->as_string} ? $authvalues->{$_->as_string} : $_->as_string;
536
537                 # Field processing
538                 eval $fieldprocessing if ($fieldprocessing);
539
540                 push @valuesarray, $value;
541             }
542             push (@fieldstab, join($fieldseparator, @valuesarray)); 
543          }
544     };
545
546     $csv->combine(@fieldstab);
547     $output .= $csv->string() . "\n";
548
549     return $output;
550
551 }
552
553
554 =head2 changeEncoding - Change the encoding of a record
555
556   my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
557
558 Changes the encoding of a record
559
560 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
561
562 C<$format> - MARC or MARCXML (required)
563
564 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
565
566 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
567
568 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)
569
570 FIXME: the from_encoding doesn't work yet
571
572 FIXME: better handling for UNIMARC, it should allow management of 100 field
573
574 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
575
576 =cut
577
578 sub changeEncoding {
579         my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
580         my $newrecord;
581         my $error;
582         unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
583         unless($to_encoding) {$to_encoding = "UTF-8"};
584         
585         # ISO-2709 Record (MARC21 or UNIMARC)
586         if (lc($format) =~ /^marc$/o) {
587                 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
588                 #       because MARC::Record doesn't directly provide us with an encoding method
589                 #       It's definitely less than idea and should be fixed eventually - kados
590                 my $marcxml; # temporary storage of MARCXML scalar
591                 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
592                 unless ($error) {
593                         ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
594                 }
595         
596         # MARCXML Record
597         } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
598                 my $marc;
599                 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
600                 unless ($error) {
601                         ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
602                 }
603         } else {
604                 $error.="Unsupported record format:".$format;
605         }
606         return ($error,$newrecord);
607 }
608
609 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
610
611   my ($bibtex) = marc2bibtex($record, $id);
612
613 Returns a BibTex scalar
614
615 C<$record> - a MARC::Record object
616
617 C<$id> - an id for the BibTex record (might be the biblionumber)
618
619 =cut
620
621
622 sub marc2bibtex {
623     my ($record, $id) = @_;
624     my $tex;
625
626     # Authors
627     my $marcauthors = GetMarcAuthors($record,C4::Context->preference("marcflavour"));
628     my $author;
629     for my $authors ( map { map { @$_ } values %$_  } @$marcauthors  ) {  
630         $author .= " and " if ($author && $$authors{value});
631         $author .= $$authors{value} if ($$authors{value}); 
632     }
633
634     # Defining the conversion hash according to the marcflavour
635     my %bh;
636     if (C4::Context->preference("marcflavour") eq "UNIMARC") {
637         
638         # FIXME, TODO : handle repeatable fields
639         # TODO : handle more types of documents
640
641         # Unimarc to bibtex hash
642         %bh = (
643
644             # Mandatory
645             author    => $author,
646             title     => $record->subfield("200", "a") || "",
647             editor    => $record->subfield("210", "g") || "",
648             publisher => $record->subfield("210", "c") || "",
649             year      => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
650
651             # Optional
652             volume  =>  $record->subfield("200", "v") || "",
653             series  =>  $record->subfield("225", "a") || "",
654             address =>  $record->subfield("210", "a") || "",
655             edition =>  $record->subfield("205", "a") || "",
656             note    =>  $record->subfield("300", "a") || "",
657             url     =>  $record->subfield("856", "u") || ""
658         );
659     } else {
660
661         # Marc21 to bibtex hash
662         %bh = (
663
664             # Mandatory
665             author    => $author,
666             title     => $record->subfield("245", "a") || "",
667             editor    => $record->subfield("260", "f") || "",
668             publisher => $record->subfield("260", "b") || "",
669             year      => $record->subfield("260", "c") || $record->subfield("260", "g") || "",
670
671             # Optional
672             # unimarc to marc21 specification says not to convert 200$v to marc21
673             series  =>  $record->subfield("490", "a") || "",
674             address =>  $record->subfield("260", "a") || "",
675             edition =>  $record->subfield("250", "a") || "",
676             note    =>  $record->subfield("500", "a") || "",
677             url     =>  $record->subfield("856", "u") || ""
678         );
679     }
680
681     $tex .= "\@book{";
682     $tex .= join(",\n", $id, map { $bh{$_} ? qq(\t$_ = "$bh{$_}") : () } keys %bh);
683     $tex .= "\n}\n";
684
685     return $tex;
686 }
687
688
689 =head1 INTERNAL FUNCTIONS
690
691 =head2 _entity_encode - Entity-encode an array of strings
692
693   my ($entity_encoded_string) = _entity_encode($string);
694
695 or
696
697   my (@entity_encoded_strings) = _entity_encode(@strings);
698
699 Entity-encode an array of strings
700
701 =cut
702
703 sub _entity_encode {
704         my @strings = @_;
705         my @strings_entity_encoded;
706         foreach my $string (@strings) {
707                 my $nfc_string = NFC($string);
708                 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
709                 push @strings_entity_encoded, $nfc_string;
710         }
711         return @strings_entity_encoded;
712 }
713
714 END { }       # module clean-up code here (global destructor)
715 1;
716 __END__
717
718 =head1 AUTHOR
719
720 Joshua Ferraro <jmf@liblime.com>
721
722 =head1 MODIFICATIONS
723
724
725 =cut