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