Bug 21395: Make perlcritic happy
[koha-equinox.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; # _entity_encode
29 use C4::Biblio; #marc2bibtex
30 use C4::Koha; #marc2csv
31 use C4::XSLT ();
32 use YAML; #marcrecords2csv
33 use Template;
34 use Text::CSV::Encoded; #marc2csv
35 use Koha::Items;
36 use Koha::SimpleMARC qw(read_field);
37 use Koha::XSLT::Base;
38 use Koha::CsvProfiles;
39 use Koha::AuthorisedValues;
40 use Carp;
41
42 use vars qw(@ISA @EXPORT);
43
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 && $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 dcxml = marc2dcxml ($marc, $xml, $biblionumber, $format);
224
225 EXAMPLE
226
227     my dcxml = marc2dcxml (undef, undef, 1, "oaidc");
228
229 Convert MARC or MARCXML to Dublin Core metadata (XSLT Transformation),
230 optionally can get an XML directly from biblio_metadata
231 without item information. This method take into consideration the syspref
232 'marcflavour' (UNIMARC, MARC21 and NORMARC).
233 Return an XML file with the format defined in C<$format>
234
235 C<$marc> - an ISO-2709 scalar or MARC::Record object
236
237 C<$xml> - a MARCXML file
238
239 C<$biblionumber> - biblionumber for database access
240
241 C<$format> - accept three type of DC formats (oaidc, srwdc, and rdfdc )
242
243 =cut
244
245 sub marc2dcxml {
246     my ( $marc, $xml, $biblionumber, $format ) = @_;
247
248     # global variables
249     my ( $marcxml, $record, $output );
250
251     # set the default path for intranet xslts
252     # differents xslts to process (OAIDC, SRWDC and RDFDC)
253     my $xsl = C4::Context->config('intrahtdocs') . '/prog/en/xslt/' .
254               C4::Context->preference('marcflavour') . 'slim2' . uc ( $format ) . '.xsl';
255
256     if ( defined $marc ) {
257         # no need to catch errors or warnings marc2marcxml do it instead
258         $marcxml = C4::Record::marc2marcxml( $marc );
259     } elsif ( not defined $xml and defined $biblionumber ) {
260         # get MARCXML biblio directly without item information
261         $marcxml = C4::Biblio::GetXmlBiblio( $biblionumber );
262     } else {
263         $marcxml = $xml;
264     }
265
266     # only proceed if MARC21 or UNIMARC; else clause is executed if marcflavour set it to NORMARC
267     # generate MARC::Record object to see if not a marcxml record
268     unless ( C4::Context->preference('marcflavour') eq 'NORMARC' ) {
269         eval { $record = MARC::Record->new_from_xml(
270                          $marcxml,
271                          'UTF-8',
272                          C4::Context->preference('marcflavour')
273                );
274         };
275     } else {
276         eval { $record = MARC::Record->new_from_xml(
277                          $marcxml,
278                         'UTF-8',
279                         'MARC21'
280                );
281         };
282     }
283
284     # conversion to MARC::Record object failed
285     if ( $@ ) {
286         croak "Creation of MARC::Record object failed.";
287     } elsif ( $record->warnings() ) {
288         carp "Warnings encountered while processing ISO-2709 record.\n";
289         my @warnings = $record->warnings();
290         foreach my $warn (@warnings) {
291             carp "\t". $warn;
292         };
293     } elsif ( $record =~ /^MARC::Record/ ) { # if OK makes xslt transformation
294         my $xslt_engine = Koha::XSLT::Base->new;
295         if ( $format =~ /^(dc|oaidc|srwdc|rdfdc)$/i ) {
296             $output = $xslt_engine->transform( $marcxml, $xsl );
297         } else {
298             croak "The format argument ($format) not accepted.\n" .
299                   "Please pass a valid format (oaidc, srwdc, or rdfdc)\n";
300         }
301         my $err = $xslt_engine->err; # error code
302         if ( $err ) {
303             croak "Error $err while processing\n";
304         } else {
305             return $output;
306         }
307     }
308 }
309
310 =head2 marc2modsxml - Convert from ISO-2709 to MODS
311
312   my $modsxml = marc2modsxml($marc);
313
314 Returns a MODS scalar
315
316 =cut
317
318 sub marc2modsxml {
319     my ($marc) = @_;
320     return _transformWithStylesheet($marc, "/prog/en/xslt/MARC21slim2MODS3-1.xsl");
321 }
322
323 =head2 marc2madsxml - Convert from ISO-2709 to MADS
324
325   my $madsxml = marc2madsxml($marc);
326
327 Returns a MADS scalar
328
329 =cut
330
331 sub marc2madsxml {
332     my ($marc) = @_;
333     return _transformWithStylesheet($marc, "/prog/en/xslt/MARC21slim2MADS.xsl");
334 }
335
336 =head2 _transformWithStylesheet - Transform a MARC record with a stylesheet
337
338     my $xml = _transformWithStylesheet($marc, $stylesheet)
339
340 Returns the XML scalar result of the transformation. $stylesheet should
341 contain the path to a stylesheet under intrahtdocs.
342
343 =cut
344
345 sub _transformWithStylesheet {
346     my ($marc, $stylesheet) = @_;
347     # grab the XML, run it through our stylesheet, push it out to the browser
348     my $xmlrecord = marc2marcxml($marc);
349     my $xslfile = C4::Context->config('intrahtdocs') . $stylesheet;
350     return C4::XSLT::engine->transform($xmlrecord, $xslfile);
351 }
352
353 sub marc2endnote {
354     my ($marc) = @_;
355         my $marc_rec_obj =  MARC::Record->new_from_usmarc($marc);
356     my ( $abstract, $f260a, $f710a );
357     my $f260 = $marc_rec_obj->field('260');
358     if ($f260) {
359         $f260a = $f260->subfield('a') if $f260;
360     }
361     my $f710 = $marc_rec_obj->field('710');
362     if ($f710) {
363         $f710a = $f710->subfield('a');
364     }
365     my $f500 = $marc_rec_obj->field('500');
366     if ($f500) {
367         $abstract = $f500->subfield('a');
368     }
369     my $fields = {
370         DB => C4::Context->preference("LibraryName"),
371         Title => $marc_rec_obj->title(),
372         Author => $marc_rec_obj->author(),
373         Publisher => $f710a,
374         City => $f260a,
375         Year => $marc_rec_obj->publication_date,
376         Abstract => $abstract,
377     };
378     my $style = new Biblio::EndnoteStyle();
379     my $template;
380     $template.= "DB - DB\n" if C4::Context->preference("LibraryName");
381     $template.="T1 - Title\n" if $marc_rec_obj->title();
382     $template.="A1 - Author\n" if $marc_rec_obj->author();
383     $template.="PB - Publisher\n" if  $f710a;
384     $template.="CY - City\n" if $f260a;
385     $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
386     $template.="AB - Abstract\n" if $abstract;
387     my ($text, $errmsg) = $style->format($template, $fields);
388     return ($text);
389
390 }
391
392 =head2 marc2csv - Convert several records from UNIMARC to CSV
393
394   my ($csv) = marc2csv($biblios, $csvprofileid, $itemnumbers);
395
396 Pre and postprocessing can be done through a YAML file
397
398 Returns a CSV scalar
399
400 C<$biblio> - a list of biblionumbers
401
402 C<$csvprofileid> - the id of the CSV profile to use for the export (see export_format.export_format_id)
403
404 C<$itemnumbers> - a list of itemnumbers to export
405
406 =cut
407
408 sub marc2csv {
409     my ($biblios, $id, $itemnumbers) = @_;
410     $itemnumbers ||= [];
411     my $output;
412     my $csv = Text::CSV::Encoded->new();
413
414     # Getting yaml file
415     my $configfile = "../tools/csv-profiles/$id.yaml";
416     my ($preprocess, $postprocess, $fieldprocessing);
417     if (-e $configfile){
418         ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
419     }
420
421     # Preprocessing
422     eval $preprocess if ($preprocess); ## no critic (StringyEval)
423
424     my $firstpass = 1;
425     if ( @$itemnumbers ) {
426         for my $itemnumber ( @$itemnumbers) {
427             my $item = Koha::Items->find( $itemnumber );
428             my $biblionumber = $item->biblio->biblionumber;
429             $output .= marcrecord2csv( $biblionumber, $id, $firstpass, $csv, $fieldprocessing, [$itemnumber] ) // '';
430             $firstpass = 0;
431         }
432     } else {
433         foreach my $biblio (@$biblios) {
434             $output .= marcrecord2csv( $biblio, $id, $firstpass, $csv, $fieldprocessing ) // '';
435             $firstpass = 0;
436         }
437     }
438
439     # Postprocessing
440     eval $postprocess if ($postprocess); ## no critic (StringyEval)
441
442     return $output;
443 }
444
445 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
446
447   my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
448
449 Returns a CSV scalar
450
451 C<$biblio> - a biblionumber
452
453 C<$csvprofileid> - the id of the CSV profile to use for the export (see export_format.export_format_id)
454
455 C<$header> - true if the headers are to be printed (typically at first pass)
456
457 C<$csv> - an already initialised Text::CSV object
458
459 C<$fieldprocessing>
460
461 C<$itemnumbers> a list of itemnumbers to export
462
463 =cut
464
465 sub marcrecord2csv {
466     my ($biblio, $id, $header, $csv, $fieldprocessing, $itemnumbers) = @_;
467     my $output;
468
469     # Getting the record
470     my $record = GetMarcBiblio({ biblionumber => $biblio });
471     return unless $record;
472     C4::Biblio::EmbedItemsInMarcBiblio({
473         marc_record  => $record,
474         biblionumber => $biblio,
475         item_numbers => $itemnumbers });
476     # Getting the framework
477     my $frameworkcode = GetFrameworkCode($biblio);
478
479     # Getting information about the csv profile
480     my $profile = Koha::CsvProfiles->find($id);
481
482     # Getting output encoding
483     my $encoding          = $profile->encoding || 'utf8';
484     # Getting separators
485     my $csvseparator      = $profile->csv_separator      || ',';
486     my $fieldseparator    = $profile->field_separator    || '#';
487     my $subfieldseparator = $profile->subfield_separator || '|';
488
489     # TODO: Be more generic (in case we have to handle other protected chars or more separators)
490     if ($csvseparator eq '\t') { $csvseparator = "\t" }
491     if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
492     if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
493     if ($csvseparator eq '\n') { $csvseparator = "\n" }
494     if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
495     if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
496
497     $csv = $csv->encoding_out($encoding) ;
498     $csv->sep_char($csvseparator);
499
500     # Getting the marcfields
501     my $marcfieldslist = $profile->content;
502
503     # Getting the marcfields as an array
504     my @marcfieldsarray = split('\|', $marcfieldslist);
505
506    # Separating the marcfields from the user-supplied headers
507     my @csv_structures;
508     foreach (@marcfieldsarray) {
509         my @result = split('=', $_, 2);
510         my $content = ( @result == 2 )
511             ? $result[1]
512             : $result[0];
513         my @fields;
514         while ( $content =~ m|(\d{3})\$?(.)?|g ) {
515             my $fieldtag = $1;
516             my $subfieldtag = $2 || undef;
517             push @fields, { fieldtag => $fieldtag, subfieldtag => $subfieldtag };
518         }
519         if ( @result == 2) {
520            push @csv_structures, { header => $result[0], content => $content, fields => \@fields };
521         } else {
522            push @csv_structures, { content => $content, fields => \@fields }
523         }
524     }
525
526     my ( @marcfieldsheaders, @csv_rows );
527     my $dbh = C4::Context->dbh;
528
529     my $field_list;
530     for my $field ( $record->fields ) {
531         my $fieldtag = $field->tag;
532         my $values;
533         if ( $field->is_control_field ) {
534             $values = $field->data();
535         } else {
536             $values->{indicator}{1} = $field->indicator(1);
537             $values->{indicator}{2} = $field->indicator(2);
538             for my $subfield ( $field->subfields ) {
539                 my $subfieldtag = $subfield->[0];
540                 my $value = $subfield->[1];
541                 push @{ $values->{$subfieldtag} }, $value;
542             }
543         }
544         # We force the key as an integer (trick for 00X and OXX fields)
545         push @{ $field_list->{fields}{0+$fieldtag} }, $values;
546     }
547
548     # For each field or subfield
549     foreach my $csv_structure (@csv_structures) {
550         my @field_values;
551         my $tags = $csv_structure->{fields};
552         my $content = $csv_structure->{content};
553
554         if ( $header ) {
555             # If we have a user-supplied header, we use it
556             if ( exists $csv_structure->{header} ) {
557                 push @marcfieldsheaders, $csv_structure->{header};
558             } else {
559                 # If not, we get the matching tag name from koha
560                 my $tag = $tags->[0];
561                 if ( $tag->{subfieldtag} ) {
562                     my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
563                     my @results = $dbh->selectrow_array( $query, {}, $tag->{fieldtag}, $tag->{subfieldtag} );
564                     push @marcfieldsheaders, $results[0];
565                 } else {
566                     my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
567                     my @results = $dbh->selectrow_array( $query, {}, $tag->{fieldtag} );
568                     push @marcfieldsheaders, $results[0];
569                 }
570             }
571         }
572
573         # TT tags exist
574         if ( $content =~ m|\[\%.*\%\]| ) {
575             my $tt = Template->new();
576             my $template = $content;
577             # Replace 00X and 0XX with X or XX
578             $content =~ s|fields.00(\d)|fields.$1|g;
579             $content =~ s|fields.0(\d{2})|fields.$1|g;
580             my $tt_output;
581             $tt->process( \$content, $field_list, \$tt_output );
582             push @csv_rows, $tt_output;
583         } else {
584             for my $tag ( @$tags ) {
585                 my @fields = $record->field( $tag->{fieldtag} );
586                 # If it is a subfield
587                 my @loop_values;
588                 if ( $tag->{subfieldtag} ) {
589                     my $av = Koha::AuthorisedValues->search_by_marc_field({ frameworkcode => $frameworkcode, tagfield => $tag->{fieldtag}, tagsubfield => $tag->{subfieldtag}, });
590                     $av = $av->count ? $av->unblessed : [];
591                     my $av_description_mapping = { map { ( $_->{authorised_value} => $_->{lib} ) } @$av };
592                     # For each field
593                     foreach my $field (@fields) {
594                         my @subfields = $field->subfield( $tag->{subfieldtag} );
595                         foreach my $subfield (@subfields) {
596                             push @loop_values, (defined $av_description_mapping->{$subfield}) ? $av_description_mapping->{$subfield} : $subfield;
597                         }
598                     }
599
600                 # Or a field
601                 } else {
602                     my $av = Koha::AuthorisedValues->search_by_marc_field({ frameworkcode => $frameworkcode, tagfield => $tag->{fieldtag}, });
603                     $av = $av->count ? $av->unblessed : [];
604                     my $authvalues = { map { ( $_->{authorised_value} => $_->{lib} ) } @$av };
605
606                     foreach my $field ( @fields ) {
607                         my $value;
608
609                         # If it is a control field
610                         if ($field->is_control_field) {
611                             $value = defined $authvalues->{$field->as_string} ? $authvalues->{$field->as_string} : $field->as_string;
612                         } else {
613                             # If it is a field, we gather all subfields, joined by the subfield separator
614                             my @subvaluesarray;
615                             my @subfields = $field->subfields;
616                             foreach my $subfield (@subfields) {
617                                 push (@subvaluesarray, defined $authvalues->{$subfield->[1]} ? $authvalues->{$subfield->[1]} : $subfield->[1]);
618                             }
619                             $value = join ($subfieldseparator, @subvaluesarray);
620                         }
621
622                         # Field processing
623                         my $marcfield = $tag->{fieldtag}; # This line fixes a retrocompatibility concern
624                                                           # The "processing" could be based on the $marcfield variable.
625                         eval $fieldprocessing if ($fieldprocessing); ## no critic (StringyEval)
626
627                         push @loop_values, $value;
628                     }
629
630                 }
631                 push @field_values, {
632                     fieldtag => $tag->{fieldtag},
633                     subfieldtag => $tag->{subfieldtag},
634                     values => \@loop_values,
635                 };
636             }
637             for my $field_value ( @field_values ) {
638                 if ( $field_value->{subfieldtag} ) {
639                     push @csv_rows, join( $subfieldseparator, @{ $field_value->{values} } );
640                 } else {
641                     push @csv_rows, join( $fieldseparator, @{ $field_value->{values} } );
642                 }
643             }
644         }
645     }
646
647
648     if ( $header ) {
649         $csv->combine(@marcfieldsheaders);
650         $output = $csv->string() . "\n";
651     }
652     $csv->combine(@csv_rows);
653     $output .= $csv->string() . "\n";
654
655     return $output;
656
657 }
658
659
660 =head2 changeEncoding - Change the encoding of a record
661
662   my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
663
664 Changes the encoding of a record
665
666 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
667
668 C<$format> - MARC or MARCXML (required)
669
670 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
671
672 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
673
674 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)
675
676 FIXME: the from_encoding doesn't work yet
677
678 FIXME: better handling for UNIMARC, it should allow management of 100 field
679
680 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
681
682 =cut
683
684 sub changeEncoding {
685         my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
686         my $newrecord;
687         my $error;
688         unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
689         unless($to_encoding) {$to_encoding = "UTF-8"};
690
691         # ISO-2709 Record (MARC21 or UNIMARC)
692         if (lc($format) =~ /^marc$/o) {
693                 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
694                 #       because MARC::Record doesn't directly provide us with an encoding method
695                 #       It's definitely less than idea and should be fixed eventually - kados
696                 my $marcxml; # temporary storage of MARCXML scalar
697                 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
698                 unless ($error) {
699                         ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
700                 }
701
702         # MARCXML Record
703         } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
704                 my $marc;
705                 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
706                 unless ($error) {
707                         ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
708                 }
709         } else {
710                 $error.="Unsupported record format:".$format;
711         }
712         return ($error,$newrecord);
713 }
714
715 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
716
717   my ($bibtex) = marc2bibtex($record, $id);
718
719 Returns a BibTex scalar
720
721 C<$record> - a MARC::Record object
722
723 C<$id> - an id for the BibTex record (might be the biblionumber)
724
725 =cut
726
727
728 sub marc2bibtex {
729     my ($record, $id) = @_;
730     my $tex;
731     my $marcflavour = C4::Context->preference("marcflavour");
732
733     # Authors
734     my $author;
735     my @texauthors;
736     my @authorFields = ('100','110','111','700','710','711');
737     @authorFields = ('700','701','702','710','711','721') if ( $marcflavour eq "UNIMARC" );
738
739     foreach my $field ( @authorFields ) {
740         # author formatted surname, firstname
741         my $texauthor = '';
742         if ( $marcflavour eq "UNIMARC" ) {
743            $texauthor = join ', ',
744            ( $record->subfield($field,"a"), $record->subfield($field,"b") );
745        } else {
746            $texauthor = $record->subfield($field,"a");
747        }
748        push @texauthors, $texauthor if $texauthor;
749     }
750     $author = join ' and ', @texauthors;
751
752     # Defining the conversion array according to the marcflavour
753     my @bh;
754     if ( $marcflavour eq "UNIMARC" ) {
755
756         # FIXME, TODO : handle repeatable fields
757         # TODO : handle more types of documents
758
759         # Unimarc to bibtex array
760         @bh = (
761
762             # Mandatory
763             author    => $author,
764             title     => $record->subfield("200", "a") || "",
765             editor    => $record->subfield("210", "g") || "",
766             publisher => $record->subfield("210", "c") || "",
767             year      => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
768
769             # Optional
770             volume  =>  $record->subfield("200", "v") || "",
771             series  =>  $record->subfield("225", "a") || "",
772             address =>  $record->subfield("210", "a") || "",
773             edition =>  $record->subfield("205", "a") || "",
774             note    =>  $record->subfield("300", "a") || "",
775             url     =>  $record->subfield("856", "u") || ""
776         );
777     } else {
778
779         # Marc21 to bibtex array
780         @bh = (
781
782             # Mandatory
783             author    => $author,
784             title     => $record->subfield("245", "a") || "",
785             editor    => $record->subfield("260", "f") || "",
786             publisher => $record->subfield("264", "b") || $record->subfield("260", "b") || "",
787             year      => $record->subfield("264", "c") || $record->subfield("260", "c") || $record->subfield("260", "g") || "",
788
789             # Optional
790             # unimarc to marc21 specification says not to convert 200$v to marc21
791             series  =>  $record->subfield("490", "a") || "",
792             address =>  $record->subfield("264", "a") || $record->subfield("260", "a") || "",
793             edition =>  $record->subfield("250", "a") || "",
794             note    =>  $record->subfield("500", "a") || "",
795             url     =>  $record->subfield("856", "u") || ""
796         );
797     }
798
799     my $BibtexExportAdditionalFields = C4::Context->preference('BibtexExportAdditionalFields');
800     my $additional_fields;
801     if ($BibtexExportAdditionalFields) {
802         $BibtexExportAdditionalFields = "$BibtexExportAdditionalFields\n\n";
803         $additional_fields = eval { YAML::Load($BibtexExportAdditionalFields); };
804         if ($@) {
805             warn "Unable to parse BibtexExportAdditionalFields : $@";
806             $additional_fields = undef;
807         }
808     }
809
810     if ( $additional_fields && $additional_fields->{'@'} ) {
811         my ( $f, $sf ) = split( /\$/, $additional_fields->{'@'} );
812         my ( $type ) = read_field( { record => $record, field => $f, subfield => $sf, field_numbers => [1] } );
813
814         if ($type) {
815             $tex .= '@' . $type . '{';
816         }
817         else {
818             $tex .= "\@book{";
819         }
820     }
821     else {
822         $tex .= "\@book{";
823     }
824
825     my @elt;
826     for ( my $i = 0 ; $i < scalar( @bh ) ; $i = $i + 2 ) {
827         next unless $bh[$i+1];
828         push @elt, qq|\t$bh[$i] = {$bh[$i+1]}|;
829     }
830     $tex .= join(",\n", $id, @elt);
831
832     if ($additional_fields) {
833         $tex .= ",\n";
834         foreach my $bibtex_tag ( keys %$additional_fields ) {
835             next if $bibtex_tag eq '@';
836
837             my @fields =
838               ref( $additional_fields->{$bibtex_tag} ) eq 'ARRAY'
839               ? @{ $additional_fields->{$bibtex_tag} }
840               : $additional_fields->{$bibtex_tag};
841
842             for my $tag (@fields) {
843                 my ( $f, $sf ) = split( /\$/, $tag );
844                 my @values = read_field( { record => $record, field => $f, subfield => $sf } );
845                 foreach my $v (@values) {
846                     $tex .= qq(\t$bibtex_tag = {$v}\n);
847                 }
848             }
849         }
850     }
851     else {
852         $tex .= "\n";
853     }
854
855     $tex .= "}\n";
856
857     return $tex;
858 }
859
860
861 =head1 INTERNAL FUNCTIONS
862
863 =head2 _entity_encode - Entity-encode an array of strings
864
865   my ($entity_encoded_string) = _entity_encode($string);
866
867 or
868
869   my (@entity_encoded_strings) = _entity_encode(@strings);
870
871 Entity-encode an array of strings
872
873 =cut
874
875 sub _entity_encode {
876         my @strings = @_;
877         my @strings_entity_encoded;
878         foreach my $string (@strings) {
879                 my $nfc_string = NFC($string);
880                 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
881                 push @strings_entity_encoded, $nfc_string;
882         }
883         return @strings_entity_encoded;
884 }
885
886 END { }       # module clean-up code here (global destructor)
887 1;
888 __END__
889
890 =head1 AUTHOR
891
892 Joshua Ferraro <jmf@liblime.com>
893
894 =head1 MODIFICATIONS
895
896
897 =cut