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