Bug 6540 - Add defaultsql command line option
[koha.git] / C4 / Record.pm
blobcecb6ed266aca1913e63d6a317ff357437fbca9f
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 = "Feature not yet implemented\n";
81 return ($error,$marc);
84 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
86 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
88 Returns a MARCXML scalar
90 C<$marc> - an ISO-2709 scalar or MARC::Record object
92 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
94 C<$flavour> - MARC21 or UNIMARC
96 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
98 =cut
100 sub marc2marcxml {
101 my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
102 my $error; # the error string
103 my $marcxml; # the final MARCXML scalar
105 # test if it's already a MARC::Record object, if not, make it one
106 my $marc_record_obj;
107 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
108 $marc_record_obj = $marc;
109 } else { # it's not a MARC::Record object, make it one
110 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
112 # conversion to MARC::Record object failed, populate $error
113 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
115 # only proceed if no errors so far
116 unless ($error) {
118 # check the record for warnings
119 my @warnings = $marc_record_obj->warnings();
120 if (@warnings) {
121 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
122 foreach my $warn (@warnings) { warn "\t".$warn };
124 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
125 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour
127 # attempt to convert the record to MARCXML
128 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
130 # record creation failed, populate $error
131 if ($@) {
132 $error .= "Creation of MARCXML failed:".$MARC::File::ERROR;
133 $error .= "Additional information:\n";
134 my @warnings = $@->warnings();
135 foreach my $warn (@warnings) { $error.=$warn."\n" };
137 # record creation was successful
138 } else {
140 # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block
141 @warnings = $marc_record_obj->warnings();
142 if (@warnings) {
143 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
144 foreach my $warn (@warnings) { warn "\t".$warn };
148 # only proceed if no errors so far
149 unless ($error) {
151 # entity encode the XML unless instructed not to
152 unless ($dont_entity_encode) {
153 my ($marcxml_entity_encoded) = _entity_encode($marcxml);
154 $marcxml = $marcxml_entity_encoded;
158 # return result to calling program
159 return ($error,$marcxml);
162 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
164 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
166 Returns an ISO-2709 scalar
168 C<$marcxml> - a MARCXML record
170 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
172 C<$flavour> - MARC21 or UNIMARC
174 =cut
176 sub marcxml2marc {
177 my ($marcxml,$encoding,$flavour) = @_;
178 my $error; # the error string
179 my $marc; # the final ISO-2709 scalar
180 unless($encoding) {$encoding = "UTF-8"}; # set the default encoding
181 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set the default MARC flavour
183 # attempt to do the conversion
184 eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
186 # record creation failed, populate $error
187 if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@;
188 $error.=$MARC::File::ERROR if ($MARC::File::ERROR);
190 # return result to calling program
191 return ($error,$marc);
194 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
196 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
198 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
200 FIXME: should return actual XML, not just an object
202 C<$marc> - an ISO-2709 scalar or MARC::Record object
204 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
206 =cut
208 sub marc2dcxml {
209 my ($marc,$qualified) = @_;
210 my $error;
211 # test if it's already a MARC::Record object, if not, make it one
212 my $marc_record_obj;
213 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
214 $marc_record_obj = $marc;
215 } else { # it's not a MARC::Record object, make it one
216 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
218 # conversion to MARC::Record object failed, populate $error
219 if ($@) {
220 $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR;
223 my $crosswalk = MARC::Crosswalk::DublinCore->new;
224 if ($qualified) {
225 $crosswalk = MARC::Crosswalk::DublinCore->new( qualified => 1 );
227 my $dcxml = $crosswalk->as_dublincore($marc_record_obj);
228 my $dcxmlfinal = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
229 $dcxmlfinal .= "<metadata
230 xmlns=\"http://example.org/myapp/\"
231 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
232 xsi:schemaLocation=\"http://example.org/myapp/ http://example.org/myapp/schema.xsd\"
233 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
234 xmlns:dcterms=\"http://purl.org/dc/terms/\">";
236 foreach my $element ( $dcxml->elements() ) {
237 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name().">\n";
239 $dcxmlfinal .= "\n</metadata>";
240 return ($error,$dcxmlfinal);
243 =head2 marc2modsxml - Convert from ISO-2709 to MODS
245 my ($error,$modsxml) = marc2modsxml($marc);
247 Returns a MODS scalar
249 =cut
251 sub marc2modsxml {
252 my ($marc) = @_;
253 # grab the XML, run it through our stylesheet, push it out to the browser
254 my $xmlrecord = marc2marcxml($marc);
255 my $xslfile = C4::Context->config('intrahtdocs')."/prog/en/xslt/MARC21slim2MODS3-1.xsl";
256 my $parser = XML::LibXML->new();
257 my $xslt = XML::LibXSLT->new();
258 my $source = $parser->parse_string($xmlrecord);
259 my $style_doc = $parser->parse_file($xslfile);
260 my $stylesheet = $xslt->parse_stylesheet($style_doc);
261 my $results = $stylesheet->transform($source);
262 my $newxmlrecord = $stylesheet->output_string($results);
263 return ($newxmlrecord);
266 sub marc2endnote {
267 my ($marc) = @_;
268 my $marc_rec_obj = MARC::Record->new_from_usmarc($marc);
269 my ( $abstract, $f260a, $f710a );
270 my $f260 = $marc_rec_obj->field('260');
271 if ($f260) {
272 $f260a = $f260->subfield('a') if $f260;
274 my $f710 = $marc_rec_obj->field('710');
275 if ($f710) {
276 $f710a = $f710->subfield('a');
278 my $f500 = $marc_rec_obj->field('500');
279 if ($f500) {
280 $abstract = $f500->subfield('a');
282 my $fields = {
283 DB => C4::Context->preference("LibraryName"),
284 Title => $marc_rec_obj->title(),
285 Author => $marc_rec_obj->author(),
286 Publisher => $f710a,
287 City => $f260a,
288 Year => $marc_rec_obj->publication_date,
289 Abstract => $abstract,
291 my $endnote;
292 my $style = new Biblio::EndnoteStyle();
293 my $template;
294 $template.= "DB - DB\n" if C4::Context->preference("LibraryName");
295 $template.="T1 - Title\n" if $marc_rec_obj->title();
296 $template.="A1 - Author\n" if $marc_rec_obj->author();
297 $template.="PB - Publisher\n" if $f710a;
298 $template.="CY - City\n" if $f260a;
299 $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
300 $template.="AB - Abstract\n" if $abstract;
301 my ($text, $errmsg) = $style->format($template, $fields);
302 return ($text);
306 =head2 marc2csv - Convert several records from UNIMARC to CSV
308 my ($csv) = marc2csv($biblios, $csvprofileid);
310 Pre and postprocessing can be done through a YAML file
312 Returns a CSV scalar
314 C<$biblio> - a list of biblionumbers
316 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)
318 =cut
320 sub marc2csv {
321 my ($biblios, $id) = @_;
322 my $output;
323 my $csv = Text::CSV::Encoded->new();
325 # Getting yaml file
326 my $configfile = "../tools/csv-profiles/$id.yaml";
327 my ($preprocess, $postprocess, $fieldprocessing);
328 if (-e $configfile){
329 ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
332 # Preprocessing
333 eval $preprocess if ($preprocess);
335 my $firstpass = 1;
336 foreach my $biblio (@$biblios) {
337 $output .= marcrecord2csv($biblio, $id, $firstpass, $csv, $fieldprocessing) ;
338 $firstpass = 0;
341 # Postprocessing
342 eval $postprocess if ($postprocess);
344 return $output;
347 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
349 my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
351 Returns a CSV scalar
353 C<$biblio> - a biblionumber
355 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)
357 C<$header> - true if the headers are to be printed (typically at first pass)
359 C<$csv> - an already initialised Text::CSV object
361 =cut
364 sub marcrecord2csv {
365 my ($biblio, $id, $header, $csv, $fieldprocessing) = @_;
366 my $output;
368 # Getting the record
369 my $record = GetMarcBiblio($biblio, 1);
370 next unless $record;
371 # Getting the framework
372 my $frameworkcode = GetFrameworkCode($biblio);
374 # Getting information about the csv profile
375 my $profile = GetCsvProfile($id);
377 # Getting output encoding
378 my $encoding = $profile->{encoding} || 'utf8';
379 # Getting separators
380 my $csvseparator = $profile->{csv_separator} || ',';
381 my $fieldseparator = $profile->{field_separator} || '#';
382 my $subfieldseparator = $profile->{subfield_separator} || '|';
384 # TODO: Be more generic (in case we have to handle other protected chars or more separators)
385 if ($csvseparator eq '\t') { $csvseparator = "\t" }
386 if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
387 if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
388 if ($csvseparator eq '\n') { $csvseparator = "\n" }
389 if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
390 if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
392 $csv = $csv->encoding_out($encoding) ;
393 $csv->sep_char($csvseparator);
395 # Getting the marcfields
396 my $marcfieldslist = $profile->{marcfields};
398 # Getting the marcfields as an array
399 my @marcfieldsarray = split('\|', $marcfieldslist);
401 # Separating the marcfields from the the user-supplied headers
402 my @marcfields;
403 foreach (@marcfieldsarray) {
404 my @result = split('=', $_);
405 if (scalar(@result) == 2) {
406 push @marcfields, { header => $result[0], field => $result[1] };
407 } else {
408 push @marcfields, { field => $result[0] }
412 # If we have to insert the headers
413 if ($header) {
414 my @marcfieldsheaders;
415 my $dbh = C4::Context->dbh;
417 # For each field or subfield
418 foreach (@marcfields) {
420 my $field = $_->{field};
421 # Remove any blank char that might have unintentionally insered into the tag name
422 $field =~ s/\s+//g;
424 # If we have a user-supplied header, we use it
425 if (exists $_->{header}) {
426 push @marcfieldsheaders, $_->{header};
427 } else {
428 # If not, we get the matching tag name from koha
429 if (index($field, '$') > 0) {
430 my ($fieldtag, $subfieldtag) = split('\$', $field);
431 my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
432 my $sth = $dbh->prepare($query);
433 $sth->execute($fieldtag, $subfieldtag);
434 my @results = $sth->fetchrow_array();
435 push @marcfieldsheaders, $results[0];
436 } else {
437 my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
438 my $sth = $dbh->prepare($query);
439 $sth->execute($field);
440 my @results = $sth->fetchrow_array();
441 push @marcfieldsheaders, $results[0];
445 $csv->combine(@marcfieldsheaders);
446 $output = $csv->string() . "\n";
449 # For each marcfield to export
450 my @fieldstab;
451 foreach (@marcfields) {
452 my $marcfield = $_->{field};
453 # If it is a subfield
454 if (index($marcfield, '$') > 0) {
455 my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
456 my @fields = $record->field($fieldtag);
457 my @tmpfields;
459 # For each field
460 foreach my $field (@fields) {
462 # We take every matching subfield
463 my @subfields = $field->subfield($subfieldtag);
464 foreach my $subfield (@subfields) {
466 # Getting authorised value
467 my $authvalues = GetKohaAuthorisedValuesFromField($fieldtag, $subfieldtag, $frameworkcode, undef);
468 push @tmpfields, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
471 push (@fieldstab, join($subfieldseparator, @tmpfields));
472 # Or a field
473 } else {
474 my @fields = ($record->field($marcfield));
475 my $authvalues = GetKohaAuthorisedValuesFromField($marcfield, undef, $frameworkcode, undef);
477 my @valuesarray;
478 foreach (@fields) {
479 my $value;
481 # Getting authorised value
482 $value = defined $authvalues->{$_->as_string} ? $authvalues->{$_->as_string} : $_->as_string;
484 # Field processing
485 eval $fieldprocessing if ($fieldprocessing);
487 push @valuesarray, $value;
489 push (@fieldstab, join($fieldseparator, @valuesarray));
493 $csv->combine(@fieldstab);
494 $output .= $csv->string() . "\n";
496 return $output;
501 =head2 changeEncoding - Change the encoding of a record
503 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
505 Changes the encoding of a record
507 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
509 C<$format> - MARC or MARCXML (required)
511 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
513 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
515 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)
517 FIXME: the from_encoding doesn't work yet
519 FIXME: better handling for UNIMARC, it should allow management of 100 field
521 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
523 =cut
525 sub changeEncoding {
526 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
527 my $newrecord;
528 my $error;
529 unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
530 unless($to_encoding) {$to_encoding = "UTF-8"};
532 # ISO-2709 Record (MARC21 or UNIMARC)
533 if (lc($format) =~ /^marc$/o) {
534 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
535 # because MARC::Record doesn't directly provide us with an encoding method
536 # It's definitely less than idea and should be fixed eventually - kados
537 my $marcxml; # temporary storage of MARCXML scalar
538 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
539 unless ($error) {
540 ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
543 # MARCXML Record
544 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
545 my $marc;
546 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
547 unless ($error) {
548 ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
550 } else {
551 $error.="Unsupported record format:".$format;
553 return ($error,$newrecord);
556 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
558 my ($bibtex) = marc2bibtex($record, $id);
560 Returns a BibTex scalar
562 C<$record> - a MARC::Record object
564 C<$id> - an id for the BibTex record (might be the biblionumber)
566 =cut
569 sub marc2bibtex {
570 my ($record, $id) = @_;
571 my $tex;
573 # Authors
574 my $marcauthors = GetMarcAuthors($record,C4::Context->preference("marcflavour"));
575 my $author;
576 for my $authors ( map { map { @$_ } values %$_ } @$marcauthors ) {
577 $author .= " and " if ($author && $$authors{value});
578 $author .= $$authors{value} if ($$authors{value});
581 # Defining the conversion hash according to the marcflavour
582 my %bh;
583 if (C4::Context->preference("marcflavour") eq "UNIMARC") {
585 # FIXME, TODO : handle repeatable fields
586 # TODO : handle more types of documents
588 # Unimarc to bibtex hash
589 %bh = (
591 # Mandatory
592 author => $author,
593 title => $record->subfield("200", "a") || "",
594 editor => $record->subfield("210", "g") || "",
595 publisher => $record->subfield("210", "c") || "",
596 year => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
598 # Optional
599 volume => $record->subfield("200", "v") || "",
600 series => $record->subfield("225", "a") || "",
601 address => $record->subfield("210", "a") || "",
602 edition => $record->subfield("205", "a") || "",
603 note => $record->subfield("300", "a") || "",
604 url => $record->subfield("856", "u") || ""
606 } else {
608 # Marc21 to bibtex hash
609 %bh = (
611 # Mandatory
612 author => $author,
613 title => $record->subfield("245", "a") || "",
614 editor => $record->subfield("260", "f") || "",
615 publisher => $record->subfield("260", "b") || "",
616 year => $record->subfield("260", "c") || $record->subfield("260", "g") || "",
618 # Optional
619 # unimarc to marc21 specification says not to convert 200$v to marc21
620 series => $record->subfield("490", "a") || "",
621 address => $record->subfield("260", "a") || "",
622 edition => $record->subfield("250", "a") || "",
623 note => $record->subfield("500", "a") || "",
624 url => $record->subfield("856", "u") || ""
628 $tex .= "\@book{";
629 $tex .= join(",\n", $id, map { $bh{$_} ? qq(\t$_ = "$bh{$_}") : () } keys %bh);
630 $tex .= "\n}\n";
632 return $tex;
636 =head1 INTERNAL FUNCTIONS
638 =head2 _entity_encode - Entity-encode an array of strings
640 my ($entity_encoded_string) = _entity_encode($string);
644 my (@entity_encoded_strings) = _entity_encode(@strings);
646 Entity-encode an array of strings
648 =cut
650 sub _entity_encode {
651 my @strings = @_;
652 my @strings_entity_encoded;
653 foreach my $string (@strings) {
654 my $nfc_string = NFC($string);
655 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
656 push @strings_entity_encoded, $nfc_string;
658 return @strings_entity_encoded;
661 END { } # module clean-up code here (global destructor)
663 __END__
665 =head1 AUTHOR
667 Joshua Ferraro <jmf@liblime.com>
669 =head1 MODIFICATIONS
672 =cut