Bug 10694: (follow-up) fix various issues
[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 $style_sheet = $xslt->parse_stylesheet($style_doc);
314     my $results = $style_sheet->transform($source);
315     my $newxmlrecord = $style_sheet->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, $itemnumbers);
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 C<$itemnumbers> - a list of itemnumbers to export
372
373 =cut
374
375 sub marc2csv {
376     my ($biblios, $id, $itemnumbers) = @_;
377     my $output;
378     my $csv = Text::CSV::Encoded->new();
379
380     # Getting yaml file
381     my $configfile = "../tools/csv-profiles/$id.yaml";
382     my ($preprocess, $postprocess, $fieldprocessing);
383     if (-e $configfile){
384         ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
385     }
386
387     # Preprocessing
388     eval $preprocess if ($preprocess);
389
390     my $firstpass = 1;
391     if ( $itemnumbers ) {
392         for my $itemnumber ( @$itemnumbers) {
393             my $biblionumber = GetBiblionumberFromItemnumber $itemnumber;
394             $output .= marcrecord2csv( $biblionumber, $id, $firstpass, $csv, $fieldprocessing, [$itemnumber] );
395             $firstpass = 0;
396         }
397     } else {
398         foreach my $biblio (@$biblios) {
399             $output .= marcrecord2csv( $biblio, $id, $firstpass, $csv, $fieldprocessing );
400             $firstpass = 0;
401         }
402     }
403
404     # Postprocessing
405     eval $postprocess if ($postprocess);
406
407     return $output;
408 }
409
410 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
411
412   my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
413
414 Returns a CSV scalar
415
416 C<$biblio> - a biblionumber
417
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)
419
420 C<$header> - true if the headers are to be printed (typically at first pass)
421
422 C<$csv> - an already initialised Text::CSV object
423
424 C<$fieldprocessing>
425
426 C<$itemnumbers> a list of itemnumbers to export
427
428 =cut
429
430
431 sub marcrecord2csv {
432     my ($biblio, $id, $header, $csv, $fieldprocessing, $itemnumbers) = @_;
433     my $output;
434
435     # Getting the record
436     my $record = GetMarcBiblio($biblio);
437     next unless $record;
438     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblio, $itemnumbers );
439     # Getting the framework
440     my $frameworkcode = GetFrameworkCode($biblio);
441
442     # Getting information about the csv profile
443     my $profile = GetCsvProfile($id);
444
445     # Getting output encoding
446     my $encoding          = $profile->{encoding} || 'utf8';
447     # Getting separators
448     my $csvseparator      = $profile->{csv_separator}      || ',';
449     my $fieldseparator    = $profile->{field_separator}    || '#';
450     my $subfieldseparator = $profile->{subfield_separator} || '|';
451
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" }
459
460     $csv = $csv->encoding_out($encoding) ;
461     $csv->sep_char($csvseparator);
462
463     # Getting the marcfields
464     my $marcfieldslist = $profile->{content};
465
466     # Getting the marcfields as an array
467     my @marcfieldsarray = split('\|', $marcfieldslist);
468
469    # Separating the marcfields from the user-supplied headers
470     my @marcfields;
471     foreach (@marcfieldsarray) {
472         my @result = split('=', $_);
473         if (scalar(@result) == 2) {
474            push @marcfields, { header => $result[0], field => $result[1] }; 
475         } else {
476            push @marcfields, { field => $result[0] }
477         }
478     }
479
480     # If we have to insert the headers
481     if ($header) {
482         my @marcfieldsheaders;
483         my $dbh   = C4::Context->dbh;
484
485         # For each field or subfield
486         foreach (@marcfields) {
487
488             my $field = $_->{field};
489         # Remove any blank char that might have unintentionally insered into the tag name
490         $field =~ s/\s+//g; 
491
492             # If we have a user-supplied header, we use it
493             if (exists $_->{header}) {
494                     push @marcfieldsheaders, $_->{header};
495             } else {
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];
504                 } else {
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];
510                 }
511             }
512         }
513         $csv->combine(@marcfieldsheaders);
514         $output = $csv->string() . "\n";        
515     }
516
517     # For each marcfield to export
518     my @fieldstab;
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);
525             my @tmpfields;
526
527             # For each field
528             foreach my $field (@fields) {
529
530                 # We take every matching subfield
531                 my @subfields = $field->subfield($subfieldtag);
532                 foreach my $subfield (@subfields) {
533
534                     # Getting authorised value
535                     my $authvalues = GetKohaAuthorisedValuesFromField($fieldtag, $subfieldtag, $frameworkcode, undef);
536                     push @tmpfields, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
537                 }
538             }
539             push (@fieldstab, join($subfieldseparator, @tmpfields));            
540         # Or a field
541         } else {
542             my @fields = ($record->field($marcfield));
543             my $authvalues = GetKohaAuthorisedValuesFromField($marcfield, undef, $frameworkcode, undef);
544
545         my @valuesarray;
546         foreach (@fields) {
547             my $value;
548
549             # If it is a control field
550             if ($_->is_control_field) {
551                 $value = defined $authvalues->{$_->as_string} ? $authvalues->{$_->as_string} : $_->as_string;
552             } else {
553                 # If it is a field, we gather all subfields, joined by the subfield separator
554                 my @subvaluesarray;
555                 my @subfields = $_->subfields;
556                 foreach my $subfield (@subfields) {
557                     push (@subvaluesarray, defined $authvalues->{$subfield->[1]} ? $authvalues->{$subfield->[1]} : $subfield->[1]);
558                 }
559                 $value = join ($subfieldseparator, @subvaluesarray);
560             }
561
562             # Field processing
563             eval $fieldprocessing if ($fieldprocessing);
564
565             push @valuesarray, $value;
566         }
567             push (@fieldstab, join($fieldseparator, @valuesarray)); 
568          }
569     };
570
571     $csv->combine(@fieldstab);
572     $output .= $csv->string() . "\n";
573
574     return $output;
575
576 }
577
578
579 =head2 changeEncoding - Change the encoding of a record
580
581   my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
582
583 Changes the encoding of a record
584
585 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
586
587 C<$format> - MARC or MARCXML (required)
588
589 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
590
591 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
592
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)
594
595 FIXME: the from_encoding doesn't work yet
596
597 FIXME: better handling for UNIMARC, it should allow management of 100 field
598
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
600
601 =cut
602
603 sub changeEncoding {
604         my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
605         my $newrecord;
606         my $error;
607         unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
608         unless($to_encoding) {$to_encoding = "UTF-8"};
609         
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);
617                 unless ($error) {
618                         ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
619                 }
620         
621         # MARCXML Record
622         } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
623                 my $marc;
624                 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
625                 unless ($error) {
626                         ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
627                 }
628         } else {
629                 $error.="Unsupported record format:".$format;
630         }
631         return ($error,$newrecord);
632 }
633
634 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
635
636   my ($bibtex) = marc2bibtex($record, $id);
637
638 Returns a BibTex scalar
639
640 C<$record> - a MARC::Record object
641
642 C<$id> - an id for the BibTex record (might be the biblionumber)
643
644 =cut
645
646
647 sub marc2bibtex {
648     my ($record, $id) = @_;
649     my $tex;
650     my $marcflavour = C4::Context->preference("marcflavour");
651
652     # Authors
653     my $author;
654     my @texauthors;
655     my @authorFields = ('100','110','111','700','710','711');
656     @authorFields = ('700','701','702','710','711','721') if ( $marcflavour eq "UNIMARC" );
657
658     foreach my $field ( @authorFields ) {
659         # author formatted surname, firstname
660         my $texauthor = '';
661         if ( $marcflavour eq "UNIMARC" ) {
662            $texauthor = join ', ',
663            ( $record->subfield($field,"a"), $record->subfield($field,"b") );
664        } else {
665            $texauthor = $record->subfield($field,"a");
666        }
667        push @texauthors, $texauthor if $texauthor;
668     }
669     $author = join ' and ', @texauthors;
670
671     # Defining the conversion hash according to the marcflavour
672     my %bh;
673     if ( $marcflavour eq "UNIMARC" ) {
674         
675         # FIXME, TODO : handle repeatable fields
676         # TODO : handle more types of documents
677
678         # Unimarc to bibtex hash
679         %bh = (
680
681             # Mandatory
682             author    => $author,
683             title     => $record->subfield("200", "a") || "",
684             editor    => $record->subfield("210", "g") || "",
685             publisher => $record->subfield("210", "c") || "",
686             year      => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
687
688             # Optional
689             volume  =>  $record->subfield("200", "v") || "",
690             series  =>  $record->subfield("225", "a") || "",
691             address =>  $record->subfield("210", "a") || "",
692             edition =>  $record->subfield("205", "a") || "",
693             note    =>  $record->subfield("300", "a") || "",
694             url     =>  $record->subfield("856", "u") || ""
695         );
696     } else {
697
698         # Marc21 to bibtex hash
699         %bh = (
700
701             # Mandatory
702             author    => $author,
703             title     => $record->subfield("245", "a") || "",
704             editor    => $record->subfield("260", "f") || "",
705         publisher => $record->subfield("264", "b") || $record->subfield("260", "b") || "",
706         year      => $record->subfield("264", "c") || $record->subfield("260", "c") || $record->subfield("260", "g") || "",
707
708             # Optional
709             # unimarc to marc21 specification says not to convert 200$v to marc21
710             series  =>  $record->subfield("490", "a") || "",
711         address =>  $record->subfield("264", "a") || $record->subfield("260", "a") || "",
712             edition =>  $record->subfield("250", "a") || "",
713             note    =>  $record->subfield("500", "a") || "",
714             url     =>  $record->subfield("856", "u") || ""
715         );
716     }
717
718     $tex .= "\@book{";
719     $tex .= join(",\n", $id, map { $bh{$_} ? qq(\t$_ = {$bh{$_}}) : () } keys %bh);
720     $tex .= "\n}\n";
721
722     return $tex;
723 }
724
725
726 =head1 INTERNAL FUNCTIONS
727
728 =head2 _entity_encode - Entity-encode an array of strings
729
730   my ($entity_encoded_string) = _entity_encode($string);
731
732 or
733
734   my (@entity_encoded_strings) = _entity_encode(@strings);
735
736 Entity-encode an array of strings
737
738 =cut
739
740 sub _entity_encode {
741         my @strings = @_;
742         my @strings_entity_encoded;
743         foreach my $string (@strings) {
744                 my $nfc_string = NFC($string);
745                 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
746                 push @strings_entity_encoded, $nfc_string;
747         }
748         return @strings_entity_encoded;
749 }
750
751 END { }       # module clean-up code here (global destructor)
752 1;
753 __END__
754
755 =head1 AUTHOR
756
757 Joshua Ferraro <jmf@liblime.com>
758
759 =head1 MODIFICATIONS
760
761
762 =cut