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