wr72054 fixing the z3950 search for acquisitions
[koha.git] / C4 / Record.pm
blob8e09adf2c384c3e2c9827ff141990a75a1a54d6d
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
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 use strict;
23 #use warnings; FIXME - Bug 2505
25 # please specify in which methods a given module is used
26 use MARC::Record; # marc2marcxml, marcxml2marc, html2marc, changeEncoding
27 use MARC::File::XML; # marc2marcxml, marcxml2marc, html2marcxml, changeEncoding
28 use MARC::Crosswalk::DublinCore; # marc2dcxml
29 use Biblio::EndnoteStyle;
30 use Unicode::Normalize; # _entity_encode
31 use XML::LibXSLT;
32 use XML::LibXML;
33 use C4::Biblio; #marc2bibtex
34 use C4::Csv; #marc2csv
35 use C4::Koha; #marc2csv
36 use YAML; #marcrecords2csv
37 use Text::CSV::Encoded; #marc2csv
39 use vars qw($VERSION @ISA @EXPORT);
41 # set the version for version checking
42 $VERSION = 3.00;
44 @ISA = qw(Exporter);
46 # only export API methods
48 @EXPORT = qw(
49 &marc2endnote
50 &marc2marc
51 &marc2marcxml
52 &marcxml2marc
53 &marc2dcxml
54 &marc2modsxml
55 &marc2bibtex
56 &marc2csv
57 &html2marcxml
58 &html2marc
59 &changeEncoding
62 =head1 NAME
64 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
66 =head1 SYNOPSIS
68 New in Koha 3.x. This module handles all record-related management functions.
70 =head1 API (EXPORTED FUNCTIONS)
72 =head2 marc2marc - Convert from one flavour of ISO-2709 to another
74 my ($error,$newmarc) = marc2marc($marc,$to_flavour,$from_flavour,$encoding);
76 Returns an ISO-2709 scalar
78 =cut
80 sub marc2marc {
81 my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
82 my $error = "Feature not yet implemented\n";
83 return ($error,$marc);
86 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
88 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
90 Returns a MARCXML scalar
92 C<$marc> - an ISO-2709 scalar or MARC::Record object
94 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
96 C<$flavour> - MARC21 or UNIMARC
98 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
100 =cut
102 sub marc2marcxml {
103 my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
104 my $error; # the error string
105 my $marcxml; # the final MARCXML scalar
107 # test if it's already a MARC::Record object, if not, make it one
108 my $marc_record_obj;
109 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
110 $marc_record_obj = $marc;
111 } else { # it's not a MARC::Record object, make it one
112 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
114 # conversion to MARC::Record object failed, populate $error
115 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
117 # only proceed if no errors so far
118 unless ($error) {
120 # check the record for warnings
121 my @warnings = $marc_record_obj->warnings();
122 if (@warnings) {
123 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
124 foreach my $warn (@warnings) { warn "\t".$warn };
126 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
127 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour
129 # attempt to convert the record to MARCXML
130 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
132 # record creation failed, populate $error
133 if ($@) {
134 $error .= "Creation of MARCXML failed:".$MARC::File::ERROR;
135 $error .= "Additional information:\n";
136 my @warnings = $@->warnings();
137 foreach my $warn (@warnings) { $error.=$warn."\n" };
139 # record creation was successful
140 } else {
142 # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block
143 @warnings = $marc_record_obj->warnings();
144 if (@warnings) {
145 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
146 foreach my $warn (@warnings) { warn "\t".$warn };
150 # only proceed if no errors so far
151 unless ($error) {
153 # entity encode the XML unless instructed not to
154 unless ($dont_entity_encode) {
155 my ($marcxml_entity_encoded) = _entity_encode($marcxml);
156 $marcxml = $marcxml_entity_encoded;
160 # return result to calling program
161 return ($error,$marcxml);
164 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
166 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
168 Returns an ISO-2709 scalar
170 C<$marcxml> - a MARCXML record
172 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
174 C<$flavour> - MARC21 or UNIMARC
176 =cut
178 sub marcxml2marc {
179 my ($marcxml,$encoding,$flavour) = @_;
180 my $error; # the error string
181 my $marc; # the final ISO-2709 scalar
182 unless($encoding) {$encoding = "UTF-8"}; # set the default encoding
183 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set the default MARC flavour
185 # attempt to do the conversion
186 eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
188 # record creation failed, populate $error
189 if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@;
190 $error.=$MARC::File::ERROR if ($MARC::File::ERROR);
192 # return result to calling program
193 return ($error,$marc);
196 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
198 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
200 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
202 FIXME: should return actual XML, not just an object
204 C<$marc> - an ISO-2709 scalar or MARC::Record object
206 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
208 =cut
210 sub marc2dcxml {
211 my ($marc,$qualified) = @_;
212 my $error;
213 # test if it's already a MARC::Record object, if not, make it one
214 my $marc_record_obj;
215 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
216 $marc_record_obj = $marc;
217 } else { # it's not a MARC::Record object, make it one
218 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
220 # conversion to MARC::Record object failed, populate $error
221 if ($@) {
222 $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR;
225 my $crosswalk = MARC::Crosswalk::DublinCore->new;
226 if ($qualified) {
227 $crosswalk = MARC::Crosswalk::DublinCore->new( qualified => 1 );
229 my $dcxml = $crosswalk->as_dublincore($marc_record_obj);
230 my $dcxmlfinal = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
231 $dcxmlfinal .= "<metadata
232 xmlns=\"http://example.org/myapp/\"
233 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
234 xsi:schemaLocation=\"http://example.org/myapp/ http://example.org/myapp/schema.xsd\"
235 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
236 xmlns:dcterms=\"http://purl.org/dc/terms/\">";
238 foreach my $element ( $dcxml->elements() ) {
239 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name().">\n";
241 $dcxmlfinal .= "\n</metadata>";
242 return ($error,$dcxmlfinal);
245 =head2 marc2modsxml - Convert from ISO-2709 to MODS
247 my ($error,$modsxml) = marc2modsxml($marc);
249 Returns a MODS scalar
251 =cut
253 sub marc2modsxml {
254 my ($marc) = @_;
255 # grab the XML, run it through our stylesheet, push it out to the browser
256 my $xmlrecord = marc2marcxml($marc);
257 my $xslfile = C4::Context->config('intrahtdocs')."/prog/en/xslt/MARC21slim2MODS3-1.xsl";
258 my $parser = XML::LibXML->new();
259 my $xslt = XML::LibXSLT->new();
260 my $source = $parser->parse_string($xmlrecord);
261 my $style_doc = $parser->parse_file($xslfile);
262 my $stylesheet = $xslt->parse_stylesheet($style_doc);
263 my $results = $stylesheet->transform($source);
264 my $newxmlrecord = $stylesheet->output_string($results);
265 return ($newxmlrecord);
268 sub marc2endnote {
269 my ($marc) = @_;
270 my $marc_rec_obj = MARC::Record->new_from_usmarc($marc);
271 my $f260 = $marc_rec_obj->field('260');
272 my $f260a = $f260->subfield('a') if $f260;
273 my $f710 = $marc_rec_obj->field('710');
274 my $f710a = $f710->subfield('a') if $f710;
275 my $f500 = $marc_rec_obj->field('500');
276 my $abstract = $f500->subfield('a') if $f500;
277 my $fields = {
278 DB => C4::Context->preference("LibraryName"),
279 Title => $marc_rec_obj->title(),
280 Author => $marc_rec_obj->author(),
281 Publisher => $f710a,
282 City => $f260a,
283 Year => $marc_rec_obj->publication_date,
284 Abstract => $abstract,
286 my $endnote;
287 my $style = new Biblio::EndnoteStyle();
288 my $template;
289 $template.= "DB - DB\n" if C4::Context->preference("LibraryName");
290 $template.="T1 - Title\n" if $marc_rec_obj->title();
291 $template.="A1 - Author\n" if $marc_rec_obj->author();
292 $template.="PB - Publisher\n" if $f710a;
293 $template.="CY - City\n" if $f260a;
294 $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
295 $template.="AB - Abstract\n" if $abstract;
296 my ($text, $errmsg) = $style->format($template, $fields);
297 return ($text);
301 =head2 marc2csv - Convert several records from UNIMARC to CSV
303 my ($csv) = marc2csv($biblios, $csvprofileid);
305 Pre and postprocessing can be done through a YAML file
307 Returns a CSV scalar
309 C<$biblio> - a list of biblionumbers
311 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)
313 =cut
315 sub marc2csv {
316 my ($biblios, $id) = @_;
317 my $output;
318 my $csv = Text::CSV::Encoded->new();
320 # Getting yaml file
321 my $configfile = "../tools/csv-profiles/$id.yaml";
322 my ($preprocess, $postprocess, $fieldprocessing);
323 if (-e $configfile){
324 ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
327 # Preprocessing
328 eval $preprocess if ($preprocess);
330 my $firstpass = 1;
331 foreach my $biblio (@$biblios) {
332 $output .= marcrecord2csv($biblio, $id, $firstpass, $csv, $fieldprocessing) ;
333 $firstpass = 0;
336 # Postprocessing
337 eval $postprocess if ($postprocess);
339 return $output;
342 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
344 my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
346 Returns a CSV scalar
348 C<$biblio> - a biblionumber
350 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)
352 C<$header> - true if the headers are to be printed (typically at first pass)
354 C<$csv> - an already initialised Text::CSV object
356 =cut
359 sub marcrecord2csv {
360 my ($biblio, $id, $header, $csv, $fieldprocessing) = @_;
361 my $output;
363 # Getting the record
364 my $record = GetMarcBiblio($biblio);
365 next unless $record;
366 # Getting the framework
367 my $frameworkcode = GetFrameworkCode($biblio);
369 # Getting information about the csv profile
370 my $profile = GetCsvProfile($id);
372 # Getting output encoding
373 my $encoding = $profile->{encoding} || 'utf8';
374 # Getting separators
375 my $csvseparator = $profile->{csv_separator} || ',';
376 my $fieldseparator = $profile->{field_separator} || '#';
377 my $subfieldseparator = $profile->{subfield_separator} || '|';
379 # TODO: Be more generic (in case we have to handle other protected chars or more separators)
380 if ($csvseparator eq '\t') { $csvseparator = "\t" }
381 if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
382 if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
383 if ($csvseparator eq '\n') { $csvseparator = "\n" }
384 if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
385 if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
387 $csv = $csv->encoding_out($encoding) ;
388 $csv->sep_char($csvseparator);
390 # Getting the marcfields
391 my $marcfieldslist = $profile->{marcfields};
393 # Getting the marcfields as an array
394 my @marcfieldsarray = split('\|', $marcfieldslist);
396 # Separating the marcfields from the the user-supplied headers
397 my @marcfields;
398 foreach (@marcfieldsarray) {
399 my @result = split('=', $_);
400 if (scalar(@result) == 2) {
401 push @marcfields, { header => $result[0], field => $result[1] };
402 } else {
403 push @marcfields, { field => $result[0] }
407 # If we have to insert the headers
408 if ($header) {
409 my @marcfieldsheaders;
410 my $dbh = C4::Context->dbh;
412 # For each field or subfield
413 foreach (@marcfields) {
415 my $field = $_->{field};
417 # If we have a user-supplied header, we use it
418 if (exists $_->{header}) {
419 push @marcfieldsheaders, $_->{header};
420 } else {
421 # If not, we get the matching tag name from koha
422 if (index($field, '$') > 0) {
423 my ($fieldtag, $subfieldtag) = split('\$', $field);
424 my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
425 my $sth = $dbh->prepare($query);
426 $sth->execute($fieldtag, $subfieldtag);
427 my @results = $sth->fetchrow_array();
428 push @marcfieldsheaders, $results[0];
429 } else {
430 my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
431 my $sth = $dbh->prepare($query);
432 $sth->execute($field);
433 my @results = $sth->fetchrow_array();
434 push @marcfieldsheaders, $results[0];
438 $csv->combine(@marcfieldsheaders);
439 $output = $csv->string() . "\n";
442 # For each marcfield to export
443 my @fieldstab;
444 foreach (@marcfields) {
445 my $marcfield = $_->{field};
446 # If it is a subfield
447 if (index($marcfield, '$') > 0) {
448 my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
449 my @fields = $record->field($fieldtag);
450 my @tmpfields;
452 # For each field
453 foreach my $field (@fields) {
455 # We take every matching subfield
456 my @subfields = $field->subfield($subfieldtag);
457 foreach my $subfield (@subfields) {
459 # Getting authorised value
460 my $authvalues = GetKohaAuthorisedValuesFromField($fieldtag, $subfieldtag, $frameworkcode, undef);
461 push @tmpfields, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
464 push (@fieldstab, join($subfieldseparator, @tmpfields));
465 # Or a field
466 } else {
467 my @fields = ($record->field($marcfield));
468 my $authvalues = GetKohaAuthorisedValuesFromField($marcfield, undef, $frameworkcode, undef);
470 my @valuesarray;
471 foreach (@fields) {
472 my $value;
474 # Getting authorised value
475 $value = defined $authvalues->{$_->as_string} ? $authvalues->{$_->as_string} : $_->as_string;
477 # Field processing
478 eval $fieldprocessing if ($fieldprocessing);
480 push @valuesarray, $value;
482 push (@fieldstab, join($fieldseparator, @valuesarray));
486 $csv->combine(@fieldstab);
487 $output .= $csv->string() . "\n";
489 return $output;
494 =head2 html2marcxml
496 my ($error,$marcxml) = html2marcxml($tags,$subfields,$values,$indicator,$ind_tag);
498 Returns a MARCXML scalar
500 this is used in addbiblio.pl and additem.pl to build the MARCXML record from
501 the form submission.
503 FIXME: this could use some better code documentation
505 =cut
507 sub html2marcxml {
508 my ($tags,$subfields,$values,$indicator,$ind_tag) = @_;
509 my $error;
510 # add the header info
511 my $marcxml= MARC::File::XML::header(C4::Context->preference('TemplateEncoding'),C4::Context->preference('marcflavour'));
513 # some flags used to figure out where in the record we are
514 my $prevvalue;
515 my $prevtag=-1;
516 my $first=1;
517 my $j = -1;
519 # handle characters that would cause the parser to choke FIXME: is there a more elegant solution?
520 for (my $i=0;$i<=@$tags;$i++){
521 @$values[$i] =~ s/&/&amp;/g;
522 @$values[$i] =~ s/</&lt;/g;
523 @$values[$i] =~ s/>/&gt;/g;
524 @$values[$i] =~ s/"/&quot;/g;
525 @$values[$i] =~ s/'/&apos;/g;
527 if ((@$tags[$i] ne $prevtag)){
528 $j++ unless (@$tags[$i] eq "");
529 #warn "IND:".substr(@$indicator[$j],0,1).substr(@$indicator[$j],1,1)." ".@$tags[$i];
530 if (!$first){
531 $marcxml.="</datafield>\n";
532 if ((@$tags[$i] > 10) && (@$values[$i] ne "")){
533 my $ind1 = substr(@$indicator[$j],0,1);
534 my $ind2 = substr(@$indicator[$j],1,1);
535 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
536 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
537 $first=0;
538 } else {
539 $first=1;
541 } else {
542 if (@$values[$i] ne "") {
543 # handle the leader
544 if (@$tags[$i] eq "000") {
545 $marcxml.="<leader>@$values[$i]</leader>\n";
546 $first=1;
547 # rest of the fixed fields
548 } elsif (@$tags[$i] lt '010') { # don't compare numerically 010 == 8
549 $marcxml.="<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
550 $first=1;
551 } else {
552 my $ind1 = substr(@$indicator[$j],0,1);
553 my $ind2 = substr(@$indicator[$j],1,1);
554 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
555 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
556 $first=0;
560 } else { # @$tags[$i] eq $prevtag
561 if (@$values[$i] eq "") {
562 } else {
563 if ($first){
564 my $ind1 = substr(@$indicator[$j],0,1);
565 my $ind2 = substr(@$indicator[$j],1,1);
566 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
567 $first=0;
569 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
572 $prevtag = @$tags[$i];
574 $marcxml.= MARC::File::XML::footer();
575 #warn $marcxml;
576 return ($error,$marcxml);
579 =head2 html2marc
581 Probably best to avoid using this ... it has some rather striking problems:
583 * saves blank subfields
585 * subfield order is hardcoded to always start with 'a' for repeatable tags (because it is hardcoded in the addfield routine).
587 * 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).
589 * the underlying routines didn't support subfield reordering or subfield repeatability.
591 I've left it in here because it could be useful if someone took the time to fix it. -- kados
593 =cut
595 sub html2marc {
596 my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
597 my $prevtag = -1;
598 my $record = MARC::Record->new();
599 # my %subfieldlist=();
600 my $prevvalue; # if tag <10
601 my $field; # if tag >=10
602 for (my $i=0; $i< @$rtags; $i++) {
603 # rebuild MARC::Record
604 # warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
605 if (@$rtags[$i] ne $prevtag) {
606 if ($prevtag < 10) {
607 if ($prevvalue) {
608 if (($prevtag ne '000') && ($prevvalue ne "")) {
609 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
610 } elsif ($prevvalue ne ""){
611 $record->leader($prevvalue);
614 } else {
615 if (($field) && ($field ne "")) {
616 $record->add_fields($field);
619 $indicators{@$rtags[$i]}.=' ';
620 # skip blank tags, I hope this works
621 if (@$rtags[$i] eq ''){
622 $prevtag = @$rtags[$i];
623 undef $field;
624 next;
626 if (@$rtags[$i] <10) {
627 $prevvalue= @$rvalues[$i];
628 undef $field;
629 } else {
630 undef $prevvalue;
631 if (@$rvalues[$i] eq "") {
632 undef $field;
633 } else {
634 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
636 # warn "1=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
638 $prevtag = @$rtags[$i];
639 } else {
640 if (@$rtags[$i] <10) {
641 $prevvalue=@$rvalues[$i];
642 } else {
643 if (length(@$rvalues[$i])>0) {
644 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
645 # warn "2=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
648 $prevtag= @$rtags[$i];
652 # the last has not been included inside the loop... do it now !
653 #use Data::Dumper;
654 #warn Dumper($field->{_subfields});
655 $record->add_fields($field) if (($field) && $field ne "");
656 #warn "HTML2MARC=".$record->as_formatted;
657 return $record;
660 =head2 changeEncoding - Change the encoding of a record
662 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
664 Changes the encoding of a record
666 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
668 C<$format> - MARC or MARCXML (required)
670 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
672 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
674 C<$from_encoding> - the encoding the record is currently in (optional, it will probably be able to tell unless there's a problem with the record)
676 FIXME: the from_encoding doesn't work yet
678 FIXME: better handling for UNIMARC, it should allow management of 100 field
680 FIXME: shouldn't have to convert to and from xml/marc just to change encoding someone needs to re-write MARC::Record's 'encoding' method to actually alter the encoding rather than just changing the leader
682 =cut
684 sub changeEncoding {
685 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
686 my $newrecord;
687 my $error;
688 unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
689 unless($to_encoding) {$to_encoding = "UTF-8"};
691 # ISO-2709 Record (MARC21 or UNIMARC)
692 if (lc($format) =~ /^marc$/o) {
693 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
694 # because MARC::Record doesn't directly provide us with an encoding method
695 # It's definitely less than idea and should be fixed eventually - kados
696 my $marcxml; # temporary storage of MARCXML scalar
697 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
698 unless ($error) {
699 ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
702 # MARCXML Record
703 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
704 my $marc;
705 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
706 unless ($error) {
707 ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
709 } else {
710 $error.="Unsupported record format:".$format;
712 return ($error,$newrecord);
715 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
717 my ($bibtex) = marc2bibtex($record, $id);
719 Returns a BibTex scalar
721 C<$record> - a MARC::Record object
723 C<$id> - an id for the BibTex record (might be the biblionumber)
725 =cut
728 sub marc2bibtex {
729 my ($record, $id) = @_;
730 my $tex;
732 # Authors
733 my $marcauthors = GetMarcAuthors($record,C4::Context->preference("marcflavour"));
734 my $author;
735 for my $authors ( map { map { @$_ } values %$_ } @$marcauthors ) {
736 $author .= " and " if ($author && $$authors{value});
737 $author .= $$authors{value} if ($$authors{value});
740 # Defining the conversion hash according to the marcflavour
741 my %bh;
742 if (C4::Context->preference("marcflavour") eq "UNIMARC") {
744 # FIXME, TODO : handle repeatable fields
745 # TODO : handle more types of documents
747 # Unimarc to bibtex hash
748 %bh = (
750 # Mandatory
751 author => $author,
752 title => $record->subfield("200", "a") || "",
753 editor => $record->subfield("210", "g") || "",
754 publisher => $record->subfield("210", "c") || "",
755 year => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
757 # Optional
758 volume => $record->subfield("200", "v") || "",
759 series => $record->subfield("225", "a") || "",
760 address => $record->subfield("210", "a") || "",
761 edition => $record->subfield("205", "a") || "",
762 note => $record->subfield("300", "a") || "",
763 url => $record->subfield("856", "u") || ""
765 } else {
767 # Marc21 to bibtex hash
768 %bh = (
770 # Mandatory
771 author => $author,
772 title => $record->subfield("245", "a") || "",
773 editor => $record->subfield("260", "f") || "",
774 publisher => $record->subfield("260", "b") || "",
775 year => $record->subfield("260", "c") || $record->subfield("260", "g") || "",
777 # Optional
778 # unimarc to marc21 specification says not to convert 200$v to marc21
779 series => $record->subfield("490", "a") || "",
780 address => $record->subfield("260", "a") || "",
781 edition => $record->subfield("250", "a") || "",
782 note => $record->subfield("500", "a") || "",
783 url => $record->subfield("856", "u") || ""
787 $tex .= "\@book{";
788 $tex .= join(",\n", $id, map { $bh{$_} ? qq(\t$_ = "$bh{$_}") : () } keys %bh);
789 $tex .= "\n}\n";
791 return $tex;
795 =head1 INTERNAL FUNCTIONS
797 =head2 _entity_encode - Entity-encode an array of strings
799 my ($entity_encoded_string) = _entity_encode($string);
803 my (@entity_encoded_strings) = _entity_encode(@strings);
805 Entity-encode an array of strings
807 =cut
809 sub _entity_encode {
810 my @strings = @_;
811 my @strings_entity_encoded;
812 foreach my $string (@strings) {
813 my $nfc_string = NFC($string);
814 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
815 push @strings_entity_encoded, $nfc_string;
817 return @strings_entity_encoded;
820 END { } # module clean-up code here (global destructor)
822 __END__
824 =head1 AUTHOR
826 Joshua Ferraro <jmf@liblime.com>
828 =head1 MODIFICATIONS
831 =cut