MT 2116: Addons to the CSV export
[koha.git] / C4 / Record.pm
blob20901b63120c49c0e241e3f57118b04a700f07f5
1 package C4::Record;
3 # Copyright 2006 (C) LibLime
4 # Joshua Ferraro <jmf@liblime.com>
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA 02111-1307 USA
22 use strict;# use warnings; #FIXME: turn off warnings before release
24 # please specify in which methods a given module is used
25 use MARC::Record; # marc2marcxml, marcxml2marc, html2marc, changeEncoding
26 use MARC::File::XML; # marc2marcxml, marcxml2marc, html2marcxml, changeEncoding
27 use MARC::Crosswalk::DublinCore; # marc2dcxml
28 use Biblio::EndnoteStyle;
29 use Unicode::Normalize; # _entity_encode
30 use XML::LibXSLT;
31 use XML::LibXML;
32 use C4::Biblio; #marc2bibtex
33 use C4::Csv; #marc2csv
34 use C4::Koha; #marc2csv
35 use YAML; #marcrecords2csv
36 use Text::CSV::Encoded; #marc2csv
38 use vars qw($VERSION @ISA @EXPORT);
40 # set the version for version checking
41 $VERSION = 3.00;
43 @ISA = qw(Exporter);
45 # only export API methods
47 @EXPORT = qw(
48 &marc2endnote
49 &marc2marc
50 &marc2marcxml
51 &marcxml2marc
52 &marc2dcxml
53 &marc2modsxml
54 &marc2bibtex
55 &marc2csv
56 &html2marcxml
57 &html2marc
58 &changeEncoding
61 =head1 NAME
63 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
65 =head1 SYNOPSIS
67 New in Koha 3.x. This module handles all record-related management functions.
69 =head1 API (EXPORTED FUNCTIONS)
71 =head2 marc2marc - Convert from one flavour of ISO-2709 to another
73 =over 4
75 my ($error,$newmarc) = marc2marc($marc,$to_flavour,$from_flavour,$encoding);
77 Returns an ISO-2709 scalar
79 =back
81 =cut
83 sub marc2marc {
84 my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
85 my $error = "Feature not yet implemented\n";
86 return ($error,$marc);
89 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
91 =over 4
93 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
95 Returns a MARCXML scalar
97 =over 2
99 C<$marc> - an ISO-2709 scalar or MARC::Record object
101 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
103 C<$flavour> - MARC21 or UNIMARC
105 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
107 =back
109 =back
111 =cut
113 sub marc2marcxml {
114 my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
115 my $error; # the error string
116 my $marcxml; # the final MARCXML scalar
118 # test if it's already a MARC::Record object, if not, make it one
119 my $marc_record_obj;
120 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
121 $marc_record_obj = $marc;
122 } else { # it's not a MARC::Record object, make it one
123 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
125 # conversion to MARC::Record object failed, populate $error
126 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
128 # only proceed if no errors so far
129 unless ($error) {
131 # check the record for warnings
132 my @warnings = $marc_record_obj->warnings();
133 if (@warnings) {
134 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
135 foreach my $warn (@warnings) { warn "\t".$warn };
137 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
138 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour
140 # attempt to convert the record to MARCXML
141 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
143 # record creation failed, populate $error
144 if ($@) {
145 $error .= "Creation of MARCXML failed:".$MARC::File::ERROR;
146 $error .= "Additional information:\n";
147 my @warnings = $@->warnings();
148 foreach my $warn (@warnings) { $error.=$warn."\n" };
150 # record creation was successful
151 } else {
153 # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block
154 @warnings = $marc_record_obj->warnings();
155 if (@warnings) {
156 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
157 foreach my $warn (@warnings) { warn "\t".$warn };
161 # only proceed if no errors so far
162 unless ($error) {
164 # entity encode the XML unless instructed not to
165 unless ($dont_entity_encode) {
166 my ($marcxml_entity_encoded) = _entity_encode($marcxml);
167 $marcxml = $marcxml_entity_encoded;
171 # return result to calling program
172 return ($error,$marcxml);
175 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
177 =over 4
179 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
181 Returns an ISO-2709 scalar
183 =over 2
185 C<$marcxml> - a MARCXML record
187 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
189 C<$flavour> - MARC21 or UNIMARC
191 =back
193 =back
195 =cut
197 sub marcxml2marc {
198 my ($marcxml,$encoding,$flavour) = @_;
199 my $error; # the error string
200 my $marc; # the final ISO-2709 scalar
201 unless($encoding) {$encoding = "UTF-8"}; # set the default encoding
202 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set the default MARC flavour
204 # attempt to do the conversion
205 eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
207 # record creation failed, populate $error
208 if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@;
209 $error.=$MARC::File::ERROR if ($MARC::File::ERROR);
211 # return result to calling program
212 return ($error,$marc);
215 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
217 =over 4
219 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
221 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
223 FIXME: should return actual XML, not just an object
225 =over 2
227 C<$marc> - an ISO-2709 scalar or MARC::Record object
229 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
231 =back
233 =back
235 =cut
237 sub marc2dcxml {
238 my ($marc,$qualified) = @_;
239 my $error;
240 # test if it's already a MARC::Record object, if not, make it one
241 my $marc_record_obj;
242 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
243 $marc_record_obj = $marc;
244 } else { # it's not a MARC::Record object, make it one
245 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
247 # conversion to MARC::Record object failed, populate $error
248 if ($@) {
249 $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR;
252 my $crosswalk = MARC::Crosswalk::DublinCore->new;
253 if ($qualified) {
254 $crosswalk = MARC::Crosswalk::DublinCore->new( qualified => 1 );
256 my $dcxml = $crosswalk->as_dublincore($marc_record_obj);
257 my $dcxmlfinal = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
258 $dcxmlfinal .= "<metadata
259 xmlns=\"http://example.org/myapp/\"
260 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
261 xsi:schemaLocation=\"http://example.org/myapp/ http://example.org/myapp/schema.xsd\"
262 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
263 xmlns:dcterms=\"http://purl.org/dc/terms/\">";
265 foreach my $element ( $dcxml->elements() ) {
266 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name().">\n";
268 $dcxmlfinal .= "\n</metadata>";
269 return ($error,$dcxmlfinal);
271 =head2 marc2modsxml - Convert from ISO-2709 to MODS
273 =over 4
275 my ($error,$modsxml) = marc2modsxml($marc);
277 Returns a MODS scalar
279 =back
281 =cut
283 sub marc2modsxml {
284 my ($marc) = @_;
285 # grab the XML, run it through our stylesheet, push it out to the browser
286 my $xmlrecord = marc2marcxml($marc);
287 my $xslfile = C4::Context->config('intrahtdocs')."/prog/en/xslt/MARC21slim2MODS3-1.xsl";
288 my $parser = XML::LibXML->new();
289 my $xslt = XML::LibXSLT->new();
290 my $source = $parser->parse_string($xmlrecord);
291 my $style_doc = $parser->parse_file($xslfile);
292 my $stylesheet = $xslt->parse_stylesheet($style_doc);
293 my $results = $stylesheet->transform($source);
294 my $newxmlrecord = $stylesheet->output_string($results);
295 return ($newxmlrecord);
298 sub marc2endnote {
299 my ($marc) = @_;
300 my $marc_rec_obj = MARC::Record->new_from_usmarc($marc);
301 my $f260 = $marc_rec_obj->field('260');
302 my $f260a = $f260->subfield('a') if $f260;
303 my $f710 = $marc_rec_obj->field('710');
304 my $f710a = $f710->subfield('a') if $f710;
305 my $f500 = $marc_rec_obj->field('500');
306 my $abstract = $f500->subfield('a') if $f500;
307 my $fields = {
308 DB => C4::Context->preference("LibraryName"),
309 Title => $marc_rec_obj->title(),
310 Author => $marc_rec_obj->author(),
311 Publisher => $f710a,
312 City => $f260a,
313 Year => $marc_rec_obj->publication_date,
314 Abstract => $abstract,
316 my $endnote;
317 my $style = new Biblio::EndnoteStyle();
318 my $template;
319 $template.= "DB - DB\n" if C4::Context->preference("LibraryName");
320 $template.="T1 - Title\n" if $marc_rec_obj->title();
321 $template.="A1 - Author\n" if $marc_rec_obj->author();
322 $template.="PB - Publisher\n" if $f710a;
323 $template.="CY - City\n" if $f260a;
324 $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
325 $template.="AB - Abstract\n" if $abstract;
326 my ($text, $errmsg) = $style->format($template, $fields);
327 return ($text);
331 =head2 marc2csv - Convert several records from UNIMARC to CSV
332 Pre and postprocessing can be done through a YAML file
334 =over 4
336 my ($csv) = marc2csv($biblios, $csvprofileid);
338 Returns a CSV scalar
340 =over 2
342 C<$biblio> - a list of biblionumbers
344 C<$csvprofileid> - the id of the CSV profile to use for the export (see export_format.export_format_id and the GetCsvProfiles function in C4::Csv)
346 =back
348 =back
350 =cut
351 sub marc2csv {
352 my ($biblios, $id) = @_;
353 my $output;
354 my $csv = Text::CSV::Encoded->new();
356 # Getting yaml file
357 my $configfile = "../tools/csv-profiles/$id.yaml";
358 my ($preprocess, $postprocess, $fieldprocessing);
359 if (-e $configfile){
360 ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
363 warn $fieldprocessing;
364 # Preprocessing
365 eval $preprocess if ($preprocess);
367 my $firstpass = 1;
368 foreach my $biblio (@$biblios) {
369 $output .= marcrecord2csv($biblio, $id, $firstpass, $csv, $fieldprocessing) ;
370 $firstpass = 0;
373 # Postprocessing
374 eval $postprocess if ($postprocess);
376 return $output;
379 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
381 =over 4
383 my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
385 Returns a CSV scalar
387 =over 2
389 C<$biblio> - a biblionumber
391 C<$csvprofileid> - the id of the CSV profile to use for the export (see export_format.export_format_id and the GetCsvProfiles function in C4::Csv)
393 C<$header> - true if the headers are to be printed (typically at first pass)
395 C<$csv> - an already initialised Text::CSV object
397 =back
399 =back
401 =cut
404 sub marcrecord2csv {
405 my ($biblio, $id, $header, $csv, $fieldprocessing) = @_;
406 my $output;
408 # Getting the record
409 my $record = GetMarcBiblio($biblio);
411 # Getting the framework
412 my $frameworkcode = GetFrameworkCode($biblio);
414 # Getting information about the csv profile
415 my $profile = GetCsvProfile($id);
417 # Getting output encoding
418 my $encoding = $profile->{encoding} || 'utf8';
419 # Getting separators
420 my $csvseparator = $profile->{csv_separator} || ',';
421 my $fieldseparator = $profile->{field_separator} || '#';
422 my $subfieldseparator = $profile->{subfield_separator} || '|';
424 # TODO: Be more generic (in case we have to handle other protected chars or more separators)
425 if ($csvseparator eq '\t') { $csvseparator = "\t" }
426 if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
427 if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
430 $csv = $csv->encoding_out($encoding) ;
431 $csv->sep_char($csvseparator);
433 # Getting the marcfields
434 my $marcfieldslist = $profile->{marcfields};
436 # Getting the marcfields as an array
437 my @marcfieldsarray = split('\|', $marcfieldslist);
439 # Separating the marcfields from the the user-supplied headers
440 my @marcfields;
441 foreach (@marcfieldsarray) {
442 my @result = split('=', $_);
443 if (scalar(@result) == 2) {
444 push @marcfields, { header => $result[0], field => $result[1] };
445 } else {
446 push @marcfields, { field => $result[0] }
450 # If we have to insert the headers
451 if ($header) {
452 my @marcfieldsheaders;
453 my $dbh = C4::Context->dbh;
455 # For each field or subfield
456 foreach (@marcfields) {
458 my $field = $_->{field};
460 # If we have a user-supplied header, we use it
461 if (exists $_->{header}) {
462 push @marcfieldsheaders, $_->{header};
463 } else {
464 # If not, we get the matching tag name from koha
465 if (index($field, '$') > 0) {
466 my ($fieldtag, $subfieldtag) = split('\$', $field);
467 my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
468 my $sth = $dbh->prepare($query);
469 $sth->execute($fieldtag, $subfieldtag);
470 my @results = $sth->fetchrow_array();
471 push @marcfieldsheaders, $results[0];
472 } else {
473 my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
474 my $sth = $dbh->prepare($query);
475 $sth->execute($field);
476 my @results = $sth->fetchrow_array();
477 push @marcfieldsheaders, $results[0];
481 $csv->combine(@marcfieldsheaders);
482 $output = $csv->string() . "\n";
485 # For each marcfield to export
486 my @fieldstab;
487 foreach (@marcfields) {
488 my $marcfield = $_->{field};
489 # If it is a subfield
490 if (index($marcfield, '$') > 0) {
491 my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
492 my @fields = $record->field($fieldtag);
493 my @tmpfields;
495 # For each field
496 foreach my $field (@fields) {
498 # We take every matching subfield
499 my @subfields = $field->subfield($subfieldtag);
500 foreach my $subfield (@subfields) {
502 # Getting authorised value
503 my $authvalues = GetKohaAuthorisedValuesFromField($fieldtag, $subfieldtag, $frameworkcode, undef);
504 push @tmpfields, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
507 push (@fieldstab, join($subfieldseparator, @tmpfields));
508 # Or a field
509 } else {
510 my @fields = ($record->field($marcfield));
511 my $authvalues = GetKohaAuthorisedValuesFromField($marcfield, undef, $frameworkcode, undef);
513 my @valuesarray;
514 foreach (@fields) {
515 my $value;
517 # Getting authorised value
518 $value = defined $authvalues->{$_->as_string} ? $authvalues->{$_->as_string} : $_->as_string;
520 # Field processing
521 eval $fieldprocessing if ($fieldprocessing);
523 push @valuesarray, $value;
525 push (@fieldstab, join($fieldseparator, @valuesarray));
529 $csv->combine(@fieldstab);
530 $output .= $csv->string() . "\n";
532 return $output;
537 =head2 html2marcxml
539 =over 4
541 my ($error,$marcxml) = html2marcxml($tags,$subfields,$values,$indicator,$ind_tag);
543 Returns a MARCXML scalar
545 this is used in addbiblio.pl and additem.pl to build the MARCXML record from
546 the form submission.
548 FIXME: this could use some better code documentation
550 =back
552 =cut
554 sub html2marcxml {
555 my ($tags,$subfields,$values,$indicator,$ind_tag) = @_;
556 my $error;
557 # add the header info
558 my $marcxml= MARC::File::XML::header(C4::Context->preference('TemplateEncoding'),C4::Context->preference('marcflavour'));
560 # some flags used to figure out where in the record we are
561 my $prevvalue;
562 my $prevtag=-1;
563 my $first=1;
564 my $j = -1;
566 # handle characters that would cause the parser to choke FIXME: is there a more elegant solution?
567 for (my $i=0;$i<=@$tags;$i++){
568 @$values[$i] =~ s/&/&amp;/g;
569 @$values[$i] =~ s/</&lt;/g;
570 @$values[$i] =~ s/>/&gt;/g;
571 @$values[$i] =~ s/"/&quot;/g;
572 @$values[$i] =~ s/'/&apos;/g;
574 if ((@$tags[$i] ne $prevtag)){
575 $j++ unless (@$tags[$i] eq "");
576 #warn "IND:".substr(@$indicator[$j],0,1).substr(@$indicator[$j],1,1)." ".@$tags[$i];
577 if (!$first){
578 $marcxml.="</datafield>\n";
579 if ((@$tags[$i] > 10) && (@$values[$i] ne "")){
580 my $ind1 = substr(@$indicator[$j],0,1);
581 my $ind2 = substr(@$indicator[$j],1,1);
582 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
583 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
584 $first=0;
585 } else {
586 $first=1;
588 } else {
589 if (@$values[$i] ne "") {
590 # handle the leader
591 if (@$tags[$i] eq "000") {
592 $marcxml.="<leader>@$values[$i]</leader>\n";
593 $first=1;
594 # rest of the fixed fields
595 } elsif (@$tags[$i] lt '010') { # don't compare numerically 010 == 8
596 $marcxml.="<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
597 $first=1;
598 } else {
599 my $ind1 = substr(@$indicator[$j],0,1);
600 my $ind2 = substr(@$indicator[$j],1,1);
601 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
602 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
603 $first=0;
607 } else { # @$tags[$i] eq $prevtag
608 if (@$values[$i] eq "") {
609 } else {
610 if ($first){
611 my $ind1 = substr(@$indicator[$j],0,1);
612 my $ind2 = substr(@$indicator[$j],1,1);
613 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
614 $first=0;
616 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
619 $prevtag = @$tags[$i];
621 $marcxml.= MARC::File::XML::footer();
622 #warn $marcxml;
623 return ($error,$marcxml);
626 =head2 html2marc
628 =over 4
630 Probably best to avoid using this ... it has some rather striking problems:
632 =over 2
634 * saves blank subfields
636 * subfield order is hardcoded to always start with 'a' for repeatable tags (because it is hardcoded in the addfield routine).
638 * only possible to specify one set of indicators for each set of tags (ie, one for all the 650s). (because they were stored in a hash with the tag as the key).
640 * the underlying routines didn't support subfield reordering or subfield repeatability.
642 =back
644 I've left it in here because it could be useful if someone took the time to fix it. -- kados
646 =back
648 =cut
650 sub html2marc {
651 my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
652 my $prevtag = -1;
653 my $record = MARC::Record->new();
654 # my %subfieldlist=();
655 my $prevvalue; # if tag <10
656 my $field; # if tag >=10
657 for (my $i=0; $i< @$rtags; $i++) {
658 # rebuild MARC::Record
659 # warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
660 if (@$rtags[$i] ne $prevtag) {
661 if ($prevtag < 10) {
662 if ($prevvalue) {
663 if (($prevtag ne '000') && ($prevvalue ne "")) {
664 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
665 } elsif ($prevvalue ne ""){
666 $record->leader($prevvalue);
669 } else {
670 if (($field) && ($field ne "")) {
671 $record->add_fields($field);
674 $indicators{@$rtags[$i]}.=' ';
675 # skip blank tags, I hope this works
676 if (@$rtags[$i] eq ''){
677 $prevtag = @$rtags[$i];
678 undef $field;
679 next;
681 if (@$rtags[$i] <10) {
682 $prevvalue= @$rvalues[$i];
683 undef $field;
684 } else {
685 undef $prevvalue;
686 if (@$rvalues[$i] eq "") {
687 undef $field;
688 } else {
689 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
691 # warn "1=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
693 $prevtag = @$rtags[$i];
694 } else {
695 if (@$rtags[$i] <10) {
696 $prevvalue=@$rvalues[$i];
697 } else {
698 if (length(@$rvalues[$i])>0) {
699 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
700 # warn "2=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
703 $prevtag= @$rtags[$i];
707 # the last has not been included inside the loop... do it now !
708 #use Data::Dumper;
709 #warn Dumper($field->{_subfields});
710 $record->add_fields($field) if (($field) && $field ne "");
711 #warn "HTML2MARC=".$record->as_formatted;
712 return $record;
715 =head2 changeEncoding - Change the encoding of a record
717 =over 4
719 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
721 Changes the encoding of a record
723 =over 2
725 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
727 C<$format> - MARC or MARCXML (required)
729 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
731 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
733 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)
735 =back
737 FIXME: the from_encoding doesn't work yet
739 FIXME: better handling for UNIMARC, it should allow management of 100 field
741 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
743 =back
745 =cut
747 sub changeEncoding {
748 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
749 my $newrecord;
750 my $error;
751 unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
752 unless($to_encoding) {$to_encoding = "UTF-8"};
754 # ISO-2709 Record (MARC21 or UNIMARC)
755 if (lc($format) =~ /^marc$/o) {
756 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
757 # because MARC::Record doesn't directly provide us with an encoding method
758 # It's definitely less than idea and should be fixed eventually - kados
759 my $marcxml; # temporary storage of MARCXML scalar
760 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
761 unless ($error) {
762 ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
765 # MARCXML Record
766 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
767 my $marc;
768 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
769 unless ($error) {
770 ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
772 } else {
773 $error.="Unsupported record format:".$format;
775 return ($error,$newrecord);
778 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
780 =over 4
782 my ($bibtex) = marc2bibtex($record, $id);
784 Returns a BibTex scalar
786 =over 2
788 C<$record> - a MARC::Record object
790 C<$id> - an id for the BibTex record (might be the biblionumber)
792 =back
794 =back
796 =cut
799 sub marc2bibtex {
800 my ($record, $id) = @_;
801 my $tex;
803 # Authors
804 my $marcauthors = GetMarcAuthors($record,C4::Context->preference("marcflavour"));
805 my $author;
806 for my $authors ( map { map { @$_ } values %$_ } @$marcauthors ) {
807 $author .= " and " if ($author && $$authors{value});
808 $author .= $$authors{value} if ($$authors{value});
811 # Defining the conversion hash according to the marcflavour
812 my %bh;
813 if (C4::Context->preference("marcflavour") eq "UNIMARC") {
815 # FIXME, TODO : handle repeatable fields
816 # TODO : handle more types of documents
818 # Unimarc to bibtex hash
819 %bh = (
821 # Mandatory
822 author => $author,
823 title => $record->subfield("200", "a") || "",
824 editor => $record->subfield("210", "g") || "",
825 publisher => $record->subfield("210", "c") || "",
826 year => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
828 # Optional
829 volume => $record->subfield("200", "v") || "",
830 series => $record->subfield("225", "a") || "",
831 address => $record->subfield("210", "a") || "",
832 edition => $record->subfield("205", "a") || "",
833 note => $record->subfield("300", "a") || "",
834 url => $record->subfield("856", "u") || ""
836 } else {
838 # Marc21 to bibtex hash
839 %bh = (
841 # Mandatory
842 author => $author,
843 title => $record->subfield("245", "a") || "",
844 editor => $record->subfield("260", "f") || "",
845 publisher => $record->subfield("260", "b") || "",
846 year => $record->subfield("260", "c") || $record->subfield("260", "g") || "",
848 # Optional
849 # unimarc to marc21 specification says not to convert 200$v to marc21
850 series => $record->subfield("490", "a") || "",
851 address => $record->subfield("260", "a") || "",
852 edition => $record->subfield("250", "a") || "",
853 note => $record->subfield("500", "a") || "",
854 url => $record->subfield("856", "u") || ""
858 $tex .= "\@book{";
859 $tex .= join(",\n", $id, map { $bh{$_} ? qq(\t$_ = "$bh{$_}") : () } keys %bh);
860 $tex .= "\n}\n";
862 return $tex;
866 =head1 INTERNAL FUNCTIONS
868 =head2 _entity_encode - Entity-encode an array of strings
870 =over 4
872 my ($entity_encoded_string) = _entity_encode($string);
876 my (@entity_encoded_strings) = _entity_encode(@strings);
878 Entity-encode an array of strings
880 =back
882 =cut
884 sub _entity_encode {
885 my @strings = @_;
886 my @strings_entity_encoded;
887 foreach my $string (@strings) {
888 my $nfc_string = NFC($string);
889 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
890 push @strings_entity_encoded, $nfc_string;
892 return @strings_entity_encoded;
895 END { } # module clean-up code here (global destructor)
897 __END__
899 =head1 AUTHOR
901 Joshua Ferraro <jmf@liblime.com>
903 =head1 MODIFICATIONS
906 =cut