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