Bug 13969: Replace calls to $sth->fetchrow* with a call to $dbh->selectrow* and Clean...
[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
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.
12 #
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.
17 #
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>.
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 Template;
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     return C4::XSLT::engine->transform($xmlrecord, $xslfile);
310 }
311
312 sub marc2endnote {
313     my ($marc) = @_;
314         my $marc_rec_obj =  MARC::Record->new_from_usmarc($marc);
315     my ( $abstract, $f260a, $f710a );
316     my $f260 = $marc_rec_obj->field('260');
317     if ($f260) {
318         $f260a = $f260->subfield('a') if $f260;
319     }
320     my $f710 = $marc_rec_obj->field('710');
321     if ($f710) {
322         $f710a = $f710->subfield('a');
323     }
324     my $f500 = $marc_rec_obj->field('500');
325     if ($f500) {
326         $abstract = $f500->subfield('a');
327     }
328         my $fields = {
329                 DB => C4::Context->preference("LibraryName"),
330                 Title => $marc_rec_obj->title(),        
331                 Author => $marc_rec_obj->author(),      
332                 Publisher => $f710a,
333                 City => $f260a,
334                 Year => $marc_rec_obj->publication_date,
335                 Abstract => $abstract,
336         };
337         my $endnote;
338         my $style = new Biblio::EndnoteStyle();
339         my $template;
340         $template.= "DB - DB\n" if C4::Context->preference("LibraryName");
341         $template.="T1 - Title\n" if $marc_rec_obj->title();
342         $template.="A1 - Author\n" if $marc_rec_obj->author();
343         $template.="PB - Publisher\n" if  $f710a;
344         $template.="CY - City\n" if $f260a;
345         $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
346         $template.="AB - Abstract\n" if $abstract;
347         my ($text, $errmsg) = $style->format($template, $fields);
348         return ($text);
349         
350 }
351
352 =head2 marc2csv - Convert several records from UNIMARC to CSV
353
354   my ($csv) = marc2csv($biblios, $csvprofileid, $itemnumbers);
355
356 Pre and postprocessing can be done through a YAML file
357
358 Returns a CSV scalar
359
360 C<$biblio> - a list of biblionumbers
361
362 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)
363
364 C<$itemnumbers> - a list of itemnumbers to export
365
366 =cut
367
368 sub marc2csv {
369     my ($biblios, $id, $itemnumbers) = @_;
370     $itemnumbers ||= [];
371     my $output;
372     my $csv = Text::CSV::Encoded->new();
373
374     # Getting yaml file
375     my $configfile = "../tools/csv-profiles/$id.yaml";
376     my ($preprocess, $postprocess, $fieldprocessing);
377     if (-e $configfile){
378         ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
379     }
380
381     # Preprocessing
382     eval $preprocess if ($preprocess);
383
384     my $firstpass = 1;
385     if ( @$itemnumbers ) {
386         for my $itemnumber ( @$itemnumbers) {
387             my $biblionumber = GetBiblionumberFromItemnumber $itemnumber;
388             $output .= marcrecord2csv( $biblionumber, $id, $firstpass, $csv, $fieldprocessing, [$itemnumber] );
389             $firstpass = 0;
390         }
391     } else {
392         foreach my $biblio (@$biblios) {
393             $output .= marcrecord2csv( $biblio, $id, $firstpass, $csv, $fieldprocessing );
394             $firstpass = 0;
395         }
396     }
397
398     # Postprocessing
399     eval $postprocess if ($postprocess);
400
401     return $output;
402 }
403
404 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
405
406   my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
407
408 Returns a CSV scalar
409
410 C<$biblio> - a biblionumber
411
412 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)
413
414 C<$header> - true if the headers are to be printed (typically at first pass)
415
416 C<$csv> - an already initialised Text::CSV object
417
418 C<$fieldprocessing>
419
420 C<$itemnumbers> a list of itemnumbers to export
421
422 =cut
423
424 sub marcrecord2csv {
425     my ($biblio, $id, $header, $csv, $fieldprocessing, $itemnumbers) = @_;
426     my $output;
427
428     # Getting the record
429     my $record = GetMarcBiblio($biblio);
430     return unless $record;
431     C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblio, $itemnumbers );
432     # Getting the framework
433     my $frameworkcode = GetFrameworkCode($biblio);
434
435     # Getting information about the csv profile
436     my $profile = GetCsvProfile($id);
437
438     # Getting output encoding
439     my $encoding          = $profile->{encoding} || 'utf8';
440     # Getting separators
441     my $csvseparator      = $profile->{csv_separator}      || ',';
442     my $fieldseparator    = $profile->{field_separator}    || '#';
443     my $subfieldseparator = $profile->{subfield_separator} || '|';
444
445     # TODO: Be more generic (in case we have to handle other protected chars or more separators)
446     if ($csvseparator eq '\t') { $csvseparator = "\t" }
447     if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
448     if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
449     if ($csvseparator eq '\n') { $csvseparator = "\n" }
450     if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
451     if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
452
453     $csv = $csv->encoding_out($encoding) ;
454     $csv->sep_char($csvseparator);
455
456     # Getting the marcfields
457     my $marcfieldslist = $profile->{content};
458
459     # Getting the marcfields as an array
460     my @marcfieldsarray = split('\|', $marcfieldslist);
461
462    # Separating the marcfields from the user-supplied headers
463     my @csv_structures;
464     foreach (@marcfieldsarray) {
465         my @result = split('=', $_, 2);
466         my $content = ( @result == 2 )
467             ? $result[1]
468             : $result[0];
469         my @fields;
470         while ( $content =~ m|(\d{3})\$?(.)?|g ) {
471             my $fieldtag = $1;
472             my $subfieldtag = $2 || undef;
473             push @fields, { fieldtag => $fieldtag, subfieldtag => $subfieldtag };
474         }
475         if ( @result == 2) {
476            push @csv_structures, { header => $result[0], content => $content, fields => \@fields };
477         } else {
478            push @csv_structures, { content => $content, fields => \@fields }
479         }
480     }
481
482     my ( @marcfieldsheaders, @csv_rows );
483     my $dbh = C4::Context->dbh;
484
485     my $field_list;
486     for my $field ( $record->fields ) {
487         my $fieldtag = $field->tag;
488         my $values;
489         if ( $field->is_control_field ) {
490             $values = $field->data();
491         } else {
492             $values->{indicator}{1} = $field->indicator(1);
493             $values->{indicator}{2} = $field->indicator(2);
494             for my $subfield ( $field->subfields ) {
495                 my $subfieldtag = $subfield->[0];
496                 my $value = $subfield->[1];
497                 push @{ $values->{$subfieldtag} }, $value;
498             }
499         }
500         # We force the key as an integer (trick for 00X and OXX fields)
501         push @{ $field_list->{fields}{0+$fieldtag} }, $values;
502     }
503
504     # For each field or subfield
505     foreach my $csv_structure (@csv_structures) {
506         my @field_values;
507         my $tags = $csv_structure->{fields};
508         my $content = $csv_structure->{content};
509
510         if ( $header ) {
511             # If we have a user-supplied header, we use it
512             if ( exists $csv_structure->{header} ) {
513                 push @marcfieldsheaders, $csv_structure->{header};
514             } else {
515                 # If not, we get the matching tag name from koha
516                 my $tag = $tags->[0];
517                 if ( $tag->{subfieldtag} ) {
518                     my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
519                     my @results = $dbh->selectrow_array( $query, {}, $tag->{fieldtag}, $tag->{subfieldtag} );
520                     push @marcfieldsheaders, $results[0];
521                 } else {
522                     my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
523                     my @results = $dbh->selectrow_array( $query, {}, $tag->{fieldtag} );
524                     push @marcfieldsheaders, $results[0];
525                 }
526             }
527         }
528
529         # TT tags exist
530         if ( $content =~ m|\[\%.*\%\]| ) {
531             my $tt = Template->new();
532             my $template = $content;
533             my $vars;
534             # Replace 00X and 0XX with X or XX
535             $content =~ s|fields.00(\d)|fields.$1|g;
536             $content =~ s|fields.0(\d{2})|fields.$1|g;
537             my $tt_output;
538             $tt->process( \$content, $field_list, \$tt_output );
539             push @csv_rows, $tt_output;
540         } else {
541             for my $tag ( @$tags ) {
542                 my @fields = $record->field( $tag->{fieldtag} );
543                 # If it is a subfield
544                 my @loop_values;
545                 if ( $tag->{subfieldtag} ) {
546                     # For each field
547                     foreach my $field (@fields) {
548                         my @subfields = $field->subfield( $tag->{subfieldtag} );
549                         foreach my $subfield (@subfields) {
550                             my $authvalues = GetKohaAuthorisedValuesFromField( $tag->{fieldtag}, $tag->{subfieldtag}, $frameworkcode, undef);
551                             push @loop_values, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
552                         }
553                     }
554
555                 # Or a field
556                 } else {
557                     my $authvalues = GetKohaAuthorisedValuesFromField( $tag->{fieldtag}, undef, $frameworkcode, undef);
558
559                     foreach my $field ( @fields ) {
560                         my $value;
561
562                         # If it is a control field
563                         if ($field->is_control_field) {
564                             $value = defined $authvalues->{$field->as_string} ? $authvalues->{$field->as_string} : $field->as_string;
565                         } else {
566                             # If it is a field, we gather all subfields, joined by the subfield separator
567                             my @subvaluesarray;
568                             my @subfields = $field->subfields;
569                             foreach my $subfield (@subfields) {
570                                 push (@subvaluesarray, defined $authvalues->{$subfield->[1]} ? $authvalues->{$subfield->[1]} : $subfield->[1]);
571                             }
572                             $value = join ($subfieldseparator, @subvaluesarray);
573                         }
574
575                         # Field processing
576                         my $marcfield = $tag->{fieldtag}; # This line fixes a retrocompatibility concern
577                                                           # The "processing" could be based on the $marcfield variable.
578                         eval $fieldprocessing if ($fieldprocessing);
579
580                         push @loop_values, $value;
581                     }
582
583                 }
584                 push @field_values, {
585                     fieldtag => $tag->{fieldtag},
586                     subfieldtag => $tag->{subfieldtag},
587                     values => \@loop_values,
588                 };
589             }
590             for my $field_value ( @field_values ) {
591                 if ( $field_value->{subfieldtag} ) {
592                     push @csv_rows, join( $subfieldseparator, @{ $field_value->{values} } );
593                 } else {
594                     push @csv_rows, join( $fieldseparator, @{ $field_value->{values} } );
595                 }
596             }
597         }
598     }
599
600
601     if ( $header ) {
602         $csv->combine(@marcfieldsheaders);
603         $output = $csv->string() . "\n";
604     }
605     $csv->combine(@csv_rows);
606     $output .= $csv->string() . "\n";
607
608     return $output;
609
610 }
611
612
613 =head2 changeEncoding - Change the encoding of a record
614
615   my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
616
617 Changes the encoding of a record
618
619 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
620
621 C<$format> - MARC or MARCXML (required)
622
623 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
624
625 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
626
627 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)
628
629 FIXME: the from_encoding doesn't work yet
630
631 FIXME: better handling for UNIMARC, it should allow management of 100 field
632
633 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
634
635 =cut
636
637 sub changeEncoding {
638         my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
639         my $newrecord;
640         my $error;
641         unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
642         unless($to_encoding) {$to_encoding = "UTF-8"};
643         
644         # ISO-2709 Record (MARC21 or UNIMARC)
645         if (lc($format) =~ /^marc$/o) {
646                 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
647                 #       because MARC::Record doesn't directly provide us with an encoding method
648                 #       It's definitely less than idea and should be fixed eventually - kados
649                 my $marcxml; # temporary storage of MARCXML scalar
650                 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
651                 unless ($error) {
652                         ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
653                 }
654         
655         # MARCXML Record
656         } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
657                 my $marc;
658                 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
659                 unless ($error) {
660                         ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
661                 }
662         } else {
663                 $error.="Unsupported record format:".$format;
664         }
665         return ($error,$newrecord);
666 }
667
668 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
669
670   my ($bibtex) = marc2bibtex($record, $id);
671
672 Returns a BibTex scalar
673
674 C<$record> - a MARC::Record object
675
676 C<$id> - an id for the BibTex record (might be the biblionumber)
677
678 =cut
679
680
681 sub marc2bibtex {
682     my ($record, $id) = @_;
683     my $tex;
684     my $marcflavour = C4::Context->preference("marcflavour");
685
686     # Authors
687     my $author;
688     my @texauthors;
689     my @authorFields = ('100','110','111','700','710','711');
690     @authorFields = ('700','701','702','710','711','721') if ( $marcflavour eq "UNIMARC" );
691
692     foreach my $field ( @authorFields ) {
693         # author formatted surname, firstname
694         my $texauthor = '';
695         if ( $marcflavour eq "UNIMARC" ) {
696            $texauthor = join ', ',
697            ( $record->subfield($field,"a"), $record->subfield($field,"b") );
698        } else {
699            $texauthor = $record->subfield($field,"a");
700        }
701        push @texauthors, $texauthor if $texauthor;
702     }
703     $author = join ' and ', @texauthors;
704
705     # Defining the conversion array according to the marcflavour
706     my @bh;
707     if ( $marcflavour eq "UNIMARC" ) {
708
709         # FIXME, TODO : handle repeatable fields
710         # TODO : handle more types of documents
711
712         # Unimarc to bibtex array
713         @bh = (
714
715             # Mandatory
716             author    => $author,
717             title     => $record->subfield("200", "a") || "",
718             editor    => $record->subfield("210", "g") || "",
719             publisher => $record->subfield("210", "c") || "",
720             year      => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
721
722             # Optional
723             volume  =>  $record->subfield("200", "v") || "",
724             series  =>  $record->subfield("225", "a") || "",
725             address =>  $record->subfield("210", "a") || "",
726             edition =>  $record->subfield("205", "a") || "",
727             note    =>  $record->subfield("300", "a") || "",
728             url     =>  $record->subfield("856", "u") || ""
729         );
730     } else {
731
732         # Marc21 to bibtex array
733         @bh = (
734
735             # Mandatory
736             author    => $author,
737             title     => $record->subfield("245", "a") || "",
738             editor    => $record->subfield("260", "f") || "",
739             publisher => $record->subfield("264", "b") || $record->subfield("260", "b") || "",
740             year      => $record->subfield("264", "c") || $record->subfield("260", "c") || $record->subfield("260", "g") || "",
741
742             # Optional
743             # unimarc to marc21 specification says not to convert 200$v to marc21
744             series  =>  $record->subfield("490", "a") || "",
745             address =>  $record->subfield("264", "a") || $record->subfield("260", "a") || "",
746             edition =>  $record->subfield("250", "a") || "",
747             note    =>  $record->subfield("500", "a") || "",
748             url     =>  $record->subfield("856", "u") || ""
749         );
750     }
751
752     $tex .= "\@book{";
753     my @elt;
754     for ( my $i = 0 ; $i < scalar( @bh ) ; $i = $i + 2 ) {
755         next unless $bh[$i+1];
756         push @elt, qq|\t$bh[$i] = {$bh[$i+1]}|;
757     }
758     $tex .= join(",\n", $id, @elt);
759     $tex .= "\n}\n";
760
761     return $tex;
762 }
763
764
765 =head1 INTERNAL FUNCTIONS
766
767 =head2 _entity_encode - Entity-encode an array of strings
768
769   my ($entity_encoded_string) = _entity_encode($string);
770
771 or
772
773   my (@entity_encoded_strings) = _entity_encode(@strings);
774
775 Entity-encode an array of strings
776
777 =cut
778
779 sub _entity_encode {
780         my @strings = @_;
781         my @strings_entity_encoded;
782         foreach my $string (@strings) {
783                 my $nfc_string = NFC($string);
784                 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
785                 push @strings_entity_encoded, $nfc_string;
786         }
787         return @strings_entity_encoded;
788 }
789
790 END { }       # module clean-up code here (global destructor)
791 1;
792 __END__
793
794 =head1 AUTHOR
795
796 Joshua Ferraro <jmf@liblime.com>
797
798 =head1 MODIFICATIONS
799
800
801 =cut