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