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