move ReservesMaxPickUpDelay to Holds Policy on Circ Prefs
[koha.git] / C4 / Record.pm
blob1acad7a8e8b1be9ff24245c0d035d1b84ea183ed
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" }
428 if ($csvseparator eq '\n') { $csvseparator = "\n" }
429 if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
430 if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
432 $csv = $csv->encoding_out($encoding) ;
433 $csv->sep_char($csvseparator);
435 # Getting the marcfields
436 my $marcfieldslist = $profile->{marcfields};
438 # Getting the marcfields as an array
439 my @marcfieldsarray = split('\|', $marcfieldslist);
441 # Separating the marcfields from the the user-supplied headers
442 my @marcfields;
443 foreach (@marcfieldsarray) {
444 my @result = split('=', $_);
445 if (scalar(@result) == 2) {
446 push @marcfields, { header => $result[0], field => $result[1] };
447 } else {
448 push @marcfields, { field => $result[0] }
452 # If we have to insert the headers
453 if ($header) {
454 my @marcfieldsheaders;
455 my $dbh = C4::Context->dbh;
457 # For each field or subfield
458 foreach (@marcfields) {
460 my $field = $_->{field};
462 # If we have a user-supplied header, we use it
463 if (exists $_->{header}) {
464 push @marcfieldsheaders, $_->{header};
465 } else {
466 # If not, we get the matching tag name from koha
467 if (index($field, '$') > 0) {
468 my ($fieldtag, $subfieldtag) = split('\$', $field);
469 my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
470 my $sth = $dbh->prepare($query);
471 $sth->execute($fieldtag, $subfieldtag);
472 my @results = $sth->fetchrow_array();
473 push @marcfieldsheaders, $results[0];
474 } else {
475 my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
476 my $sth = $dbh->prepare($query);
477 $sth->execute($field);
478 my @results = $sth->fetchrow_array();
479 push @marcfieldsheaders, $results[0];
483 $csv->combine(@marcfieldsheaders);
484 $output = $csv->string() . "\n";
487 # For each marcfield to export
488 my @fieldstab;
489 foreach (@marcfields) {
490 my $marcfield = $_->{field};
491 # If it is a subfield
492 if (index($marcfield, '$') > 0) {
493 my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
494 my @fields = $record->field($fieldtag);
495 my @tmpfields;
497 # For each field
498 foreach my $field (@fields) {
500 # We take every matching subfield
501 my @subfields = $field->subfield($subfieldtag);
502 foreach my $subfield (@subfields) {
504 # Getting authorised value
505 my $authvalues = GetKohaAuthorisedValuesFromField($fieldtag, $subfieldtag, $frameworkcode, undef);
506 push @tmpfields, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
509 push (@fieldstab, join($subfieldseparator, @tmpfields));
510 # Or a field
511 } else {
512 my @fields = ($record->field($marcfield));
513 my $authvalues = GetKohaAuthorisedValuesFromField($marcfield, undef, $frameworkcode, undef);
515 my @valuesarray;
516 foreach (@fields) {
517 my $value;
519 # Getting authorised value
520 $value = defined $authvalues->{$_->as_string} ? $authvalues->{$_->as_string} : $_->as_string;
522 # Field processing
523 eval $fieldprocessing if ($fieldprocessing);
525 push @valuesarray, $value;
527 push (@fieldstab, join($fieldseparator, @valuesarray));
531 $csv->combine(@fieldstab);
532 $output .= $csv->string() . "\n";
534 return $output;
539 =head2 html2marcxml
541 =over 4
543 my ($error,$marcxml) = html2marcxml($tags,$subfields,$values,$indicator,$ind_tag);
545 Returns a MARCXML scalar
547 this is used in addbiblio.pl and additem.pl to build the MARCXML record from
548 the form submission.
550 FIXME: this could use some better code documentation
552 =back
554 =cut
556 sub html2marcxml {
557 my ($tags,$subfields,$values,$indicator,$ind_tag) = @_;
558 my $error;
559 # add the header info
560 my $marcxml= MARC::File::XML::header(C4::Context->preference('TemplateEncoding'),C4::Context->preference('marcflavour'));
562 # some flags used to figure out where in the record we are
563 my $prevvalue;
564 my $prevtag=-1;
565 my $first=1;
566 my $j = -1;
568 # handle characters that would cause the parser to choke FIXME: is there a more elegant solution?
569 for (my $i=0;$i<=@$tags;$i++){
570 @$values[$i] =~ s/&/&amp;/g;
571 @$values[$i] =~ s/</&lt;/g;
572 @$values[$i] =~ s/>/&gt;/g;
573 @$values[$i] =~ s/"/&quot;/g;
574 @$values[$i] =~ s/'/&apos;/g;
576 if ((@$tags[$i] ne $prevtag)){
577 $j++ unless (@$tags[$i] eq "");
578 #warn "IND:".substr(@$indicator[$j],0,1).substr(@$indicator[$j],1,1)." ".@$tags[$i];
579 if (!$first){
580 $marcxml.="</datafield>\n";
581 if ((@$tags[$i] > 10) && (@$values[$i] ne "")){
582 my $ind1 = substr(@$indicator[$j],0,1);
583 my $ind2 = substr(@$indicator[$j],1,1);
584 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
585 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
586 $first=0;
587 } else {
588 $first=1;
590 } else {
591 if (@$values[$i] ne "") {
592 # handle the leader
593 if (@$tags[$i] eq "000") {
594 $marcxml.="<leader>@$values[$i]</leader>\n";
595 $first=1;
596 # rest of the fixed fields
597 } elsif (@$tags[$i] lt '010') { # don't compare numerically 010 == 8
598 $marcxml.="<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
599 $first=1;
600 } else {
601 my $ind1 = substr(@$indicator[$j],0,1);
602 my $ind2 = substr(@$indicator[$j],1,1);
603 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
604 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
605 $first=0;
609 } else { # @$tags[$i] eq $prevtag
610 if (@$values[$i] eq "") {
611 } else {
612 if ($first){
613 my $ind1 = substr(@$indicator[$j],0,1);
614 my $ind2 = substr(@$indicator[$j],1,1);
615 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
616 $first=0;
618 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
621 $prevtag = @$tags[$i];
623 $marcxml.= MARC::File::XML::footer();
624 #warn $marcxml;
625 return ($error,$marcxml);
628 =head2 html2marc
630 =over 4
632 Probably best to avoid using this ... it has some rather striking problems:
634 =over 2
636 * saves blank subfields
638 * subfield order is hardcoded to always start with 'a' for repeatable tags (because it is hardcoded in the addfield routine).
640 * 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).
642 * the underlying routines didn't support subfield reordering or subfield repeatability.
644 =back
646 I've left it in here because it could be useful if someone took the time to fix it. -- kados
648 =back
650 =cut
652 sub html2marc {
653 my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
654 my $prevtag = -1;
655 my $record = MARC::Record->new();
656 # my %subfieldlist=();
657 my $prevvalue; # if tag <10
658 my $field; # if tag >=10
659 for (my $i=0; $i< @$rtags; $i++) {
660 # rebuild MARC::Record
661 # warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
662 if (@$rtags[$i] ne $prevtag) {
663 if ($prevtag < 10) {
664 if ($prevvalue) {
665 if (($prevtag ne '000') && ($prevvalue ne "")) {
666 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
667 } elsif ($prevvalue ne ""){
668 $record->leader($prevvalue);
671 } else {
672 if (($field) && ($field ne "")) {
673 $record->add_fields($field);
676 $indicators{@$rtags[$i]}.=' ';
677 # skip blank tags, I hope this works
678 if (@$rtags[$i] eq ''){
679 $prevtag = @$rtags[$i];
680 undef $field;
681 next;
683 if (@$rtags[$i] <10) {
684 $prevvalue= @$rvalues[$i];
685 undef $field;
686 } else {
687 undef $prevvalue;
688 if (@$rvalues[$i] eq "") {
689 undef $field;
690 } else {
691 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
693 # warn "1=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
695 $prevtag = @$rtags[$i];
696 } else {
697 if (@$rtags[$i] <10) {
698 $prevvalue=@$rvalues[$i];
699 } else {
700 if (length(@$rvalues[$i])>0) {
701 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
702 # warn "2=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
705 $prevtag= @$rtags[$i];
709 # the last has not been included inside the loop... do it now !
710 #use Data::Dumper;
711 #warn Dumper($field->{_subfields});
712 $record->add_fields($field) if (($field) && $field ne "");
713 #warn "HTML2MARC=".$record->as_formatted;
714 return $record;
717 =head2 changeEncoding - Change the encoding of a record
719 =over 4
721 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
723 Changes the encoding of a record
725 =over 2
727 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
729 C<$format> - MARC or MARCXML (required)
731 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
733 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
735 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)
737 =back
739 FIXME: the from_encoding doesn't work yet
741 FIXME: better handling for UNIMARC, it should allow management of 100 field
743 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
745 =back
747 =cut
749 sub changeEncoding {
750 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
751 my $newrecord;
752 my $error;
753 unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
754 unless($to_encoding) {$to_encoding = "UTF-8"};
756 # ISO-2709 Record (MARC21 or UNIMARC)
757 if (lc($format) =~ /^marc$/o) {
758 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
759 # because MARC::Record doesn't directly provide us with an encoding method
760 # It's definitely less than idea and should be fixed eventually - kados
761 my $marcxml; # temporary storage of MARCXML scalar
762 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
763 unless ($error) {
764 ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
767 # MARCXML Record
768 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
769 my $marc;
770 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
771 unless ($error) {
772 ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
774 } else {
775 $error.="Unsupported record format:".$format;
777 return ($error,$newrecord);
780 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
782 =over 4
784 my ($bibtex) = marc2bibtex($record, $id);
786 Returns a BibTex scalar
788 =over 2
790 C<$record> - a MARC::Record object
792 C<$id> - an id for the BibTex record (might be the biblionumber)
794 =back
796 =back
798 =cut
801 sub marc2bibtex {
802 my ($record, $id) = @_;
803 my $tex;
805 # Authors
806 my $marcauthors = GetMarcAuthors($record,C4::Context->preference("marcflavour"));
807 my $author;
808 for my $authors ( map { map { @$_ } values %$_ } @$marcauthors ) {
809 $author .= " and " if ($author && $$authors{value});
810 $author .= $$authors{value} if ($$authors{value});
813 # Defining the conversion hash according to the marcflavour
814 my %bh;
815 if (C4::Context->preference("marcflavour") eq "UNIMARC") {
817 # FIXME, TODO : handle repeatable fields
818 # TODO : handle more types of documents
820 # Unimarc to bibtex hash
821 %bh = (
823 # Mandatory
824 author => $author,
825 title => $record->subfield("200", "a") || "",
826 editor => $record->subfield("210", "g") || "",
827 publisher => $record->subfield("210", "c") || "",
828 year => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
830 # Optional
831 volume => $record->subfield("200", "v") || "",
832 series => $record->subfield("225", "a") || "",
833 address => $record->subfield("210", "a") || "",
834 edition => $record->subfield("205", "a") || "",
835 note => $record->subfield("300", "a") || "",
836 url => $record->subfield("856", "u") || ""
838 } else {
840 # Marc21 to bibtex hash
841 %bh = (
843 # Mandatory
844 author => $author,
845 title => $record->subfield("245", "a") || "",
846 editor => $record->subfield("260", "f") || "",
847 publisher => $record->subfield("260", "b") || "",
848 year => $record->subfield("260", "c") || $record->subfield("260", "g") || "",
850 # Optional
851 # unimarc to marc21 specification says not to convert 200$v to marc21
852 series => $record->subfield("490", "a") || "",
853 address => $record->subfield("260", "a") || "",
854 edition => $record->subfield("250", "a") || "",
855 note => $record->subfield("500", "a") || "",
856 url => $record->subfield("856", "u") || ""
860 $tex .= "\@book{";
861 $tex .= join(",\n", $id, map { $bh{$_} ? qq(\t$_ = "$bh{$_}") : () } keys %bh);
862 $tex .= "\n}\n";
864 return $tex;
868 =head1 INTERNAL FUNCTIONS
870 =head2 _entity_encode - Entity-encode an array of strings
872 =over 4
874 my ($entity_encoded_string) = _entity_encode($string);
878 my (@entity_encoded_strings) = _entity_encode(@strings);
880 Entity-encode an array of strings
882 =back
884 =cut
886 sub _entity_encode {
887 my @strings = @_;
888 my @strings_entity_encoded;
889 foreach my $string (@strings) {
890 my $nfc_string = NFC($string);
891 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
892 push @strings_entity_encoded, $nfc_string;
894 return @strings_entity_encoded;
897 END { } # module clean-up code here (global destructor)
899 __END__
901 =head1 AUTHOR
903 Joshua Ferraro <jmf@liblime.com>
905 =head1 MODIFICATIONS
908 =cut