Merge remote-tracking branch 'origin/new/bug_5668'
[koha.git] / C4 / Record.pm
blob89bde3227f04f003f4615ce0941eba49b174b07a
1 package C4::Record;
3 # Copyright 2006 (C) LibLime
4 # Parts copyright 2010 BibLibre
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, changeEncoding
27 use MARC::File::XML; # marc2marcxml, marcxml2marc, 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 &changeEncoding
60 =head1 NAME
62 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
64 =head1 SYNOPSIS
66 New in Koha 3.x. This module handles all record-related management functions.
68 =head1 API (EXPORTED FUNCTIONS)
70 =head2 marc2marc - Convert from one flavour of ISO-2709 to another
72 my ($error,$newmarc) = marc2marc($marc,$to_flavour,$from_flavour,$encoding);
74 Returns an ISO-2709 scalar
76 =cut
78 sub marc2marc {
79 my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
80 my $error;
81 if ($to_flavour =~ m/marcstd/) {
82 my $marc_record_obj;
83 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
84 $marc_record_obj = $marc;
85 } else { # it's not a MARC::Record object, make it one
86 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
88 # conversion to MARC::Record object failed, populate $error
89 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
91 unless ($error) {
92 my @privatefields;
93 foreach my $field ($marc_record_obj->fields()) {
94 if ($field->tag() =~ m/9/ && ($field->tag() != '490' || C4::Context->preference("marcflavour") eq 'UNIMARC')) {
95 push @privatefields, $field;
96 } elsif (! ($field->is_control_field())) {
97 $field->delete_subfield(code => '9') if ($field->subfield('9'));
100 $marc_record_obj->delete_field($_) for @privatefields;
101 $marc = $marc_record_obj->as_usmarc();
103 } else {
104 $error = "Feature not yet implemented\n";
106 return ($error,$marc);
109 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
111 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
113 Returns a MARCXML scalar
115 C<$marc> - an ISO-2709 scalar or MARC::Record object
117 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
119 C<$flavour> - MARC21 or UNIMARC
121 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
123 =cut
125 sub marc2marcxml {
126 my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
127 my $error; # the error string
128 my $marcxml; # the final MARCXML scalar
130 # test if it's already a MARC::Record object, if not, make it one
131 my $marc_record_obj;
132 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
133 $marc_record_obj = $marc;
134 } else { # it's not a MARC::Record object, make it one
135 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
137 # conversion to MARC::Record object failed, populate $error
138 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
140 # only proceed if no errors so far
141 unless ($error) {
143 # check the record for warnings
144 my @warnings = $marc_record_obj->warnings();
145 if (@warnings) {
146 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
147 foreach my $warn (@warnings) { warn "\t".$warn };
149 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
150 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour
152 # attempt to convert the record to MARCXML
153 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
155 # record creation failed, populate $error
156 if ($@) {
157 $error .= "Creation of MARCXML failed:".$MARC::File::ERROR;
158 $error .= "Additional information:\n";
159 my @warnings = $@->warnings();
160 foreach my $warn (@warnings) { $error.=$warn."\n" };
162 # record creation was successful
163 } else {
165 # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block
166 @warnings = $marc_record_obj->warnings();
167 if (@warnings) {
168 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
169 foreach my $warn (@warnings) { warn "\t".$warn };
173 # only proceed if no errors so far
174 unless ($error) {
176 # entity encode the XML unless instructed not to
177 unless ($dont_entity_encode) {
178 my ($marcxml_entity_encoded) = _entity_encode($marcxml);
179 $marcxml = $marcxml_entity_encoded;
183 # return result to calling program
184 return ($error,$marcxml);
187 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
189 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
191 Returns an ISO-2709 scalar
193 C<$marcxml> - a MARCXML record
195 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
197 C<$flavour> - MARC21 or UNIMARC
199 =cut
201 sub marcxml2marc {
202 my ($marcxml,$encoding,$flavour) = @_;
203 my $error; # the error string
204 my $marc; # the final ISO-2709 scalar
205 unless($encoding) {$encoding = "UTF-8"}; # set the default encoding
206 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set the default MARC flavour
208 # attempt to do the conversion
209 eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
211 # record creation failed, populate $error
212 if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@;
213 $error.=$MARC::File::ERROR if ($MARC::File::ERROR);
215 # return result to calling program
216 return ($error,$marc);
219 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
221 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
223 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
225 FIXME: should return actual XML, not just an object
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 =cut
233 sub marc2dcxml {
234 my ($marc,$qualified) = @_;
235 my $error;
236 # test if it's already a MARC::Record object, if not, make it one
237 my $marc_record_obj;
238 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
239 $marc_record_obj = $marc;
240 } else { # it's not a MARC::Record object, make it one
241 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
243 # conversion to MARC::Record object failed, populate $error
244 if ($@) {
245 $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR;
248 my $crosswalk = MARC::Crosswalk::DublinCore->new;
249 if ($qualified) {
250 $crosswalk = MARC::Crosswalk::DublinCore->new( qualified => 1 );
252 my $dcxml = $crosswalk->as_dublincore($marc_record_obj);
253 my $dcxmlfinal = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
254 $dcxmlfinal .= "<metadata
255 xmlns=\"http://example.org/myapp/\"
256 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
257 xsi:schemaLocation=\"http://example.org/myapp/ http://example.org/myapp/schema.xsd\"
258 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
259 xmlns:dcterms=\"http://purl.org/dc/terms/\">";
261 foreach my $element ( $dcxml->elements() ) {
262 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name().">\n";
264 $dcxmlfinal .= "\n</metadata>";
265 return ($error,$dcxmlfinal);
268 =head2 marc2modsxml - Convert from ISO-2709 to MODS
270 my ($error,$modsxml) = marc2modsxml($marc);
272 Returns a MODS scalar
274 =cut
276 sub marc2modsxml {
277 my ($marc) = @_;
278 # grab the XML, run it through our stylesheet, push it out to the browser
279 my $xmlrecord = marc2marcxml($marc);
280 my $xslfile = C4::Context->config('intrahtdocs')."/prog/en/xslt/MARC21slim2MODS3-1.xsl";
281 my $parser = XML::LibXML->new();
282 my $xslt = XML::LibXSLT->new();
283 my $source = $parser->parse_string($xmlrecord);
284 my $style_doc = $parser->parse_file($xslfile);
285 my $stylesheet = $xslt->parse_stylesheet($style_doc);
286 my $results = $stylesheet->transform($source);
287 my $newxmlrecord = $stylesheet->output_string($results);
288 return ($newxmlrecord);
291 sub marc2endnote {
292 my ($marc) = @_;
293 my $marc_rec_obj = MARC::Record->new_from_usmarc($marc);
294 my ( $abstract, $f260a, $f710a );
295 my $f260 = $marc_rec_obj->field('260');
296 if ($f260) {
297 $f260a = $f260->subfield('a') if $f260;
299 my $f710 = $marc_rec_obj->field('710');
300 if ($f710) {
301 $f710a = $f710->subfield('a');
303 my $f500 = $marc_rec_obj->field('500');
304 if ($f500) {
305 $abstract = $f500->subfield('a');
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
333 my ($csv) = marc2csv($biblios, $csvprofileid);
335 Pre and postprocessing can be done through a YAML file
337 Returns a CSV scalar
339 C<$biblio> - a list of biblionumbers
341 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)
343 =cut
345 sub marc2csv {
346 my ($biblios, $id) = @_;
347 my $output;
348 my $csv = Text::CSV::Encoded->new();
350 # Getting yaml file
351 my $configfile = "../tools/csv-profiles/$id.yaml";
352 my ($preprocess, $postprocess, $fieldprocessing);
353 if (-e $configfile){
354 ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
357 # Preprocessing
358 eval $preprocess if ($preprocess);
360 my $firstpass = 1;
361 foreach my $biblio (@$biblios) {
362 $output .= marcrecord2csv($biblio, $id, $firstpass, $csv, $fieldprocessing) ;
363 $firstpass = 0;
366 # Postprocessing
367 eval $postprocess if ($postprocess);
369 return $output;
372 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
374 my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
376 Returns a CSV scalar
378 C<$biblio> - a biblionumber
380 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)
382 C<$header> - true if the headers are to be printed (typically at first pass)
384 C<$csv> - an already initialised Text::CSV object
386 =cut
389 sub marcrecord2csv {
390 my ($biblio, $id, $header, $csv, $fieldprocessing) = @_;
391 my $output;
393 # Getting the record
394 my $record = GetMarcBiblio($biblio, 1);
395 next unless $record;
396 # Getting the framework
397 my $frameworkcode = GetFrameworkCode($biblio);
399 # Getting information about the csv profile
400 my $profile = GetCsvProfile($id);
402 # Getting output encoding
403 my $encoding = $profile->{encoding} || 'utf8';
404 # Getting separators
405 my $csvseparator = $profile->{csv_separator} || ',';
406 my $fieldseparator = $profile->{field_separator} || '#';
407 my $subfieldseparator = $profile->{subfield_separator} || '|';
409 # TODO: Be more generic (in case we have to handle other protected chars or more separators)
410 if ($csvseparator eq '\t') { $csvseparator = "\t" }
411 if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
412 if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
413 if ($csvseparator eq '\n') { $csvseparator = "\n" }
414 if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
415 if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
417 $csv = $csv->encoding_out($encoding) ;
418 $csv->sep_char($csvseparator);
420 # Getting the marcfields
421 my $marcfieldslist = $profile->{marcfields};
423 # Getting the marcfields as an array
424 my @marcfieldsarray = split('\|', $marcfieldslist);
426 # Separating the marcfields from the user-supplied headers
427 my @marcfields;
428 foreach (@marcfieldsarray) {
429 my @result = split('=', $_);
430 if (scalar(@result) == 2) {
431 push @marcfields, { header => $result[0], field => $result[1] };
432 } else {
433 push @marcfields, { field => $result[0] }
437 # If we have to insert the headers
438 if ($header) {
439 my @marcfieldsheaders;
440 my $dbh = C4::Context->dbh;
442 # For each field or subfield
443 foreach (@marcfields) {
445 my $field = $_->{field};
446 # Remove any blank char that might have unintentionally insered into the tag name
447 $field =~ s/\s+//g;
449 # If we have a user-supplied header, we use it
450 if (exists $_->{header}) {
451 push @marcfieldsheaders, $_->{header};
452 } else {
453 # If not, we get the matching tag name from koha
454 if (index($field, '$') > 0) {
455 my ($fieldtag, $subfieldtag) = split('\$', $field);
456 my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
457 my $sth = $dbh->prepare($query);
458 $sth->execute($fieldtag, $subfieldtag);
459 my @results = $sth->fetchrow_array();
460 push @marcfieldsheaders, $results[0];
461 } else {
462 my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
463 my $sth = $dbh->prepare($query);
464 $sth->execute($field);
465 my @results = $sth->fetchrow_array();
466 push @marcfieldsheaders, $results[0];
470 $csv->combine(@marcfieldsheaders);
471 $output = $csv->string() . "\n";
474 # For each marcfield to export
475 my @fieldstab;
476 foreach (@marcfields) {
477 my $marcfield = $_->{field};
478 # If it is a subfield
479 if (index($marcfield, '$') > 0) {
480 my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
481 my @fields = $record->field($fieldtag);
482 my @tmpfields;
484 # For each field
485 foreach my $field (@fields) {
487 # We take every matching subfield
488 my @subfields = $field->subfield($subfieldtag);
489 foreach my $subfield (@subfields) {
491 # Getting authorised value
492 my $authvalues = GetKohaAuthorisedValuesFromField($fieldtag, $subfieldtag, $frameworkcode, undef);
493 push @tmpfields, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
496 push (@fieldstab, join($subfieldseparator, @tmpfields));
497 # Or a field
498 } else {
499 my @fields = ($record->field($marcfield));
500 my $authvalues = GetKohaAuthorisedValuesFromField($marcfield, undef, $frameworkcode, undef);
502 my @valuesarray;
503 foreach (@fields) {
504 my $value;
506 # Getting authorised value
507 $value = defined $authvalues->{$_->as_string} ? $authvalues->{$_->as_string} : $_->as_string;
509 # Field processing
510 eval $fieldprocessing if ($fieldprocessing);
512 push @valuesarray, $value;
514 push (@fieldstab, join($fieldseparator, @valuesarray));
518 $csv->combine(@fieldstab);
519 $output .= $csv->string() . "\n";
521 return $output;
526 =head2 changeEncoding - Change the encoding of a record
528 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
530 Changes the encoding of a record
532 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
534 C<$format> - MARC or MARCXML (required)
536 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
538 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
540 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)
542 FIXME: the from_encoding doesn't work yet
544 FIXME: better handling for UNIMARC, it should allow management of 100 field
546 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
548 =cut
550 sub changeEncoding {
551 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
552 my $newrecord;
553 my $error;
554 unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
555 unless($to_encoding) {$to_encoding = "UTF-8"};
557 # ISO-2709 Record (MARC21 or UNIMARC)
558 if (lc($format) =~ /^marc$/o) {
559 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
560 # because MARC::Record doesn't directly provide us with an encoding method
561 # It's definitely less than idea and should be fixed eventually - kados
562 my $marcxml; # temporary storage of MARCXML scalar
563 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
564 unless ($error) {
565 ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
568 # MARCXML Record
569 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
570 my $marc;
571 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
572 unless ($error) {
573 ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
575 } else {
576 $error.="Unsupported record format:".$format;
578 return ($error,$newrecord);
581 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
583 my ($bibtex) = marc2bibtex($record, $id);
585 Returns a BibTex scalar
587 C<$record> - a MARC::Record object
589 C<$id> - an id for the BibTex record (might be the biblionumber)
591 =cut
594 sub marc2bibtex {
595 my ($record, $id) = @_;
596 my $tex;
598 # Authors
599 my $marcauthors = GetMarcAuthors($record,C4::Context->preference("marcflavour"));
600 my $author;
601 for my $authors ( map { map { @$_ } values %$_ } @$marcauthors ) {
602 $author .= " and " if ($author && $$authors{value});
603 $author .= $$authors{value} if ($$authors{value});
606 # Defining the conversion hash according to the marcflavour
607 my %bh;
608 if (C4::Context->preference("marcflavour") eq "UNIMARC") {
610 # FIXME, TODO : handle repeatable fields
611 # TODO : handle more types of documents
613 # Unimarc to bibtex hash
614 %bh = (
616 # Mandatory
617 author => $author,
618 title => $record->subfield("200", "a") || "",
619 editor => $record->subfield("210", "g") || "",
620 publisher => $record->subfield("210", "c") || "",
621 year => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
623 # Optional
624 volume => $record->subfield("200", "v") || "",
625 series => $record->subfield("225", "a") || "",
626 address => $record->subfield("210", "a") || "",
627 edition => $record->subfield("205", "a") || "",
628 note => $record->subfield("300", "a") || "",
629 url => $record->subfield("856", "u") || ""
631 } else {
633 # Marc21 to bibtex hash
634 %bh = (
636 # Mandatory
637 author => $author,
638 title => $record->subfield("245", "a") || "",
639 editor => $record->subfield("260", "f") || "",
640 publisher => $record->subfield("260", "b") || "",
641 year => $record->subfield("260", "c") || $record->subfield("260", "g") || "",
643 # Optional
644 # unimarc to marc21 specification says not to convert 200$v to marc21
645 series => $record->subfield("490", "a") || "",
646 address => $record->subfield("260", "a") || "",
647 edition => $record->subfield("250", "a") || "",
648 note => $record->subfield("500", "a") || "",
649 url => $record->subfield("856", "u") || ""
653 $tex .= "\@book{";
654 $tex .= join(",\n", $id, map { $bh{$_} ? qq(\t$_ = "$bh{$_}") : () } keys %bh);
655 $tex .= "\n}\n";
657 return $tex;
661 =head1 INTERNAL FUNCTIONS
663 =head2 _entity_encode - Entity-encode an array of strings
665 my ($entity_encoded_string) = _entity_encode($string);
669 my (@entity_encoded_strings) = _entity_encode(@strings);
671 Entity-encode an array of strings
673 =cut
675 sub _entity_encode {
676 my @strings = @_;
677 my @strings_entity_encoded;
678 foreach my $string (@strings) {
679 my $nfc_string = NFC($string);
680 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
681 push @strings_entity_encoded, $nfc_string;
683 return @strings_entity_encoded;
686 END { } # module clean-up code here (global destructor)
688 __END__
690 =head1 AUTHOR
692 Joshua Ferraro <jmf@liblime.com>
694 =head1 MODIFICATIONS
697 =cut