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
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
32 use C4::Biblio; #marc2bibtex
33 use C4::Csv; #marc2csv
34 use Text::CSV; #marc2csv
36 use vars qw($VERSION @ISA @EXPORT);
38 # set the version for version checking
43 # only export API methods
62 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
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
74 my ($error,$newmarc) = marc2marc($marc,$to_flavour,$from_flavour,$encoding);
76 Returns an ISO-2709 scalar
83 my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
84 my $error = "Feature not yet implemented\n";
85 return ($error,$marc);
88 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
92 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
94 Returns a MARCXML scalar
98 C<$marc> - an ISO-2709 scalar or MARC::Record object
100 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
102 C<$flavour> - MARC21 or UNIMARC
104 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
113 my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
114 my $error; # the error string
115 my $marcxml; # the final MARCXML scalar
117 # test if it's already a MARC::Record object, if not, make it one
119 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
120 $marc_record_obj = $marc;
121 } else { # it's not a MARC::Record object, make it one
122 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
124 # conversion to MARC::Record object failed, populate $error
125 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
127 # only proceed if no errors so far
130 # check the record for warnings
131 my @warnings = $marc_record_obj->warnings();
133 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
134 foreach my $warn (@warnings) { warn "\t".$warn };
136 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
137 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour
139 # attempt to convert the record to MARCXML
140 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
142 # record creation failed, populate $error
144 $error .= "Creation of MARCXML failed:".$MARC::File::ERROR;
145 $error .= "Additional information:\n";
146 my @warnings = $@->warnings();
147 foreach my $warn (@warnings) { $error.=$warn."\n" };
149 # record creation was successful
152 # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block
153 @warnings = $marc_record_obj->warnings();
155 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
156 foreach my $warn (@warnings) { warn "\t".$warn };
160 # only proceed if no errors so far
163 # entity encode the XML unless instructed not to
164 unless ($dont_entity_encode) {
165 my ($marcxml_entity_encoded) = _entity_encode($marcxml);
166 $marcxml = $marcxml_entity_encoded;
170 # return result to calling program
171 return ($error,$marcxml);
174 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
178 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
180 Returns an ISO-2709 scalar
184 C<$marcxml> - a MARCXML record
186 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
188 C<$flavour> - MARC21 or UNIMARC
197 my ($marcxml,$encoding,$flavour) = @_;
198 my $error; # the error string
199 my $marc; # the final ISO-2709 scalar
200 unless($encoding) {$encoding = "UTF-8"}; # set the default encoding
201 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set the default MARC flavour
203 # attempt to do the conversion
204 eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
206 # record creation failed, populate $error
207 if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@;
208 $error.=$MARC::File::ERROR if ($MARC::File::ERROR);
210 # return result to calling program
211 return ($error,$marc);
214 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
218 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
220 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
222 FIXME: should return actual XML, not just an object
226 C<$marc> - an ISO-2709 scalar or MARC::Record object
228 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
237 my ($marc,$qualified) = @_;
239 # test if it's already a MARC::Record object, if not, make it one
241 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
242 $marc_record_obj = $marc;
243 } else { # it's not a MARC::Record object, make it one
244 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
246 # conversion to MARC::Record object failed, populate $error
248 $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR;
251 my $crosswalk = MARC::Crosswalk::DublinCore->new;
253 $crosswalk = MARC::Crosswalk::DublinCore->new( qualified => 1 );
255 my $dcxml = $crosswalk->as_dublincore($marc_record_obj);
256 my $dcxmlfinal = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
257 $dcxmlfinal .= "<metadata
258 xmlns=\"http://example.org/myapp/\"
259 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
260 xsi:schemaLocation=\"http://example.org/myapp/ http://example.org/myapp/schema.xsd\"
261 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
262 xmlns:dcterms=\"http://purl.org/dc/terms/\">";
264 foreach my $element ( $dcxml->elements() ) {
265 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name().">\n";
267 $dcxmlfinal .= "\n</metadata>";
268 return ($error,$dcxmlfinal);
270 =head2 marc2modsxml - Convert from ISO-2709 to MODS
274 my ($error,$modsxml) = marc2modsxml($marc);
276 Returns a MODS scalar
284 # grab the XML, run it through our stylesheet, push it out to the browser
285 my $xmlrecord = marc2marcxml($marc);
286 my $xslfile = C4::Context->config('intrahtdocs')."/prog/en/xslt/MARC21slim2MODS3-1.xsl";
287 my $parser = XML::LibXML->new();
288 my $xslt = XML::LibXSLT->new();
289 my $source = $parser->parse_string($xmlrecord);
290 my $style_doc = $parser->parse_file($xslfile);
291 my $stylesheet = $xslt->parse_stylesheet($style_doc);
292 my $results = $stylesheet->transform($source);
293 my $newxmlrecord = $stylesheet->output_string($results);
294 return ($newxmlrecord);
299 my $marc_rec_obj = MARC::Record->new_from_usmarc($marc);
300 my $f260 = $marc_rec_obj->field('260');
301 my $f260a = $f260->subfield('a') if $f260;
302 my $f710 = $marc_rec_obj->field('710');
303 my $f710a = $f710->subfield('a') if $f710;
304 my $f500 = $marc_rec_obj->field('500');
305 my $abstract = $f500->subfield('a') if $f500;
307 DB => C4::Context->preference("LibraryName"),
308 Title => $marc_rec_obj->title(),
309 Author => $marc_rec_obj->author(),
312 Year => $marc_rec_obj->publication_date,
313 Abstract => $abstract,
316 my $style = new Biblio::EndnoteStyle();
318 $template.= "DB - DB\n" if C4::Context->preference("LibraryName");
319 $template.="T1 - Title\n" if $marc_rec_obj->title();
320 $template.="A1 - Author\n" if $marc_rec_obj->author();
321 $template.="PB - Publisher\n" if $f710a;
322 $template.="CY - City\n" if $f260a;
323 $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
324 $template.="AB - Abstract\n" if $abstract;
325 my ($text, $errmsg) = $style->format($template, $fields);
330 =head2 marc2csv - Convert from UNIMARC to CSV
334 my ($csv) = marc2csv($record, $csvprofileid);
340 C<$record> - a MARC::Record object
342 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)
344 C<$header> - true if the headers are to be printed (typically at first pass)
354 my ($record, $id, $header) = @_;
357 # Get the information about the csv profile
358 my $profile = GetCsvProfile($id);
361 my $csvseparator = $profile->{csv_separator} || ',';
362 my $fieldseparator = $profile->{field_separator} || '#';
363 my $subfieldseparator = $profile->{subfield_separator} || '|';
365 # TODO: Be more generic (in case we have to handle other protected chars or more separators)
366 if ($csvseparator eq '\t') { $csvseparator = "\t" }
367 if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
368 if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
371 my $csv = Text::CSV->new({ sep_char => $csvseparator });
373 # Getting the marcfields
374 my $marcfieldslist = $profile->{marcfields};
376 # Getting the marcfields as an array
377 my @marcfieldsarray = split('\|', $marcfieldslist);
379 # Separating the marcfields from the the user-supplied headers
381 foreach (@marcfieldsarray) {
382 my @result = split('=', $_);
383 if (scalar(@result) == 2) {
384 push @marcfields, { header => $result[0], field => $result[1] };
386 push @marcfields, { field => $result[0] }
390 # If we have to insert the headers
392 my @marcfieldsheaders;
393 my $dbh = C4::Context->dbh;
395 # For each field or subfield
396 foreach (@marcfields) {
398 my $field = $_->{field};
400 # If we have a user-supplied header, we use it
401 if (exists $_->{header}) {
402 push @marcfieldsheaders, $_->{header};
405 # If not, we get the matching tag name from koha
406 if (index($field, '$') > 0) {
407 my ($fieldtag, $subfieldtag) = split('\$', $field);
408 my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
409 my $sth = $dbh->prepare($query);
410 $sth->execute($fieldtag, $subfieldtag);
411 my @results = $sth->fetchrow_array();
412 warn "subfield $fieldtag, $subfieldtag";
413 push @marcfieldsheaders, $results[0];
415 my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
416 my $sth = $dbh->prepare($query);
417 $sth->execute($field);
418 my @results = $sth->fetchrow_array();
419 warn "field $results[0]";
420 push @marcfieldsheaders, $results[0];
424 $csv->combine(@marcfieldsheaders);
425 $output = $csv->string() . "\n";
428 # For each marcfield to export
430 foreach (@marcfields) {
431 my $marcfield = $_->{field};
432 # If it is a subfield
433 if (index($marcfield, '$') > 0) {
434 my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
435 my @fields = $record->field($fieldtag);
439 foreach my $field (@fields) {
441 # We take every matching subfield
442 my @subfields = $field->subfield($subfieldtag);
443 foreach my $subfield (@subfields) {
444 push @tmpfields, $subfield;
447 push (@fieldstab, join($subfieldseparator, @tmpfields));
450 my @fields = ($record->field($marcfield));
451 push (@fieldstab, join($fieldseparator, map($_->as_string(), @fields)));
455 $csv->combine(@fieldstab);
456 $output .= $csv->string() . "\n";
467 my ($error,$marcxml) = html2marcxml($tags,$subfields,$values,$indicator,$ind_tag);
469 Returns a MARCXML scalar
471 this is used in addbiblio.pl and additem.pl to build the MARCXML record from
474 FIXME: this could use some better code documentation
481 my ($tags,$subfields,$values,$indicator,$ind_tag) = @_;
483 # add the header info
484 my $marcxml= MARC::File::XML::header(C4::Context->preference('TemplateEncoding'),C4::Context->preference('marcflavour'));
486 # some flags used to figure out where in the record we are
492 # handle characters that would cause the parser to choke FIXME: is there a more elegant solution?
493 for (my $i=0;$i<=@$tags;$i++){
494 @$values[$i] =~ s/&/&/g;
495 @$values[$i] =~ s/</</g;
496 @$values[$i] =~ s/>/>/g;
497 @$values[$i] =~ s/"/"/g;
498 @$values[$i] =~ s/'/'/g;
500 if ((@$tags[$i] ne $prevtag)){
501 $j++ unless (@$tags[$i] eq "");
502 #warn "IND:".substr(@$indicator[$j],0,1).substr(@$indicator[$j],1,1)." ".@$tags[$i];
504 $marcxml.="</datafield>\n";
505 if ((@$tags[$i] > 10) && (@$values[$i] ne "")){
506 my $ind1 = substr(@$indicator[$j],0,1);
507 my $ind2 = substr(@$indicator[$j],1,1);
508 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
509 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
515 if (@$values[$i] ne "") {
517 if (@$tags[$i] eq "000") {
518 $marcxml.="<leader>@$values[$i]</leader>\n";
520 # rest of the fixed fields
521 } elsif (@$tags[$i] lt '010') { # don't compare numerically 010 == 8
522 $marcxml.="<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
525 my $ind1 = substr(@$indicator[$j],0,1);
526 my $ind2 = substr(@$indicator[$j],1,1);
527 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
528 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
533 } else { # @$tags[$i] eq $prevtag
534 if (@$values[$i] eq "") {
537 my $ind1 = substr(@$indicator[$j],0,1);
538 my $ind2 = substr(@$indicator[$j],1,1);
539 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
542 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
545 $prevtag = @$tags[$i];
547 $marcxml.= MARC::File::XML::footer();
549 return ($error,$marcxml);
556 Probably best to avoid using this ... it has some rather striking problems:
560 * saves blank subfields
562 * subfield order is hardcoded to always start with 'a' for repeatable tags (because it is hardcoded in the addfield routine).
564 * 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).
566 * the underlying routines didn't support subfield reordering or subfield repeatability.
570 I've left it in here because it could be useful if someone took the time to fix it. -- kados
577 my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
579 my $record = MARC::Record->new();
580 # my %subfieldlist=();
581 my $prevvalue; # if tag <10
582 my $field; # if tag >=10
583 for (my $i=0; $i< @$rtags; $i++) {
584 # rebuild MARC::Record
585 # warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
586 if (@$rtags[$i] ne $prevtag) {
589 if (($prevtag ne '000') && ($prevvalue ne "")) {
590 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
591 } elsif ($prevvalue ne ""){
592 $record->leader($prevvalue);
596 if (($field) && ($field ne "")) {
597 $record->add_fields($field);
600 $indicators{@$rtags[$i]}.=' ';
601 # skip blank tags, I hope this works
602 if (@$rtags[$i] eq ''){
603 $prevtag = @$rtags[$i];
607 if (@$rtags[$i] <10) {
608 $prevvalue= @$rvalues[$i];
612 if (@$rvalues[$i] eq "") {
615 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
617 # warn "1=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
619 $prevtag = @$rtags[$i];
621 if (@$rtags[$i] <10) {
622 $prevvalue=@$rvalues[$i];
624 if (length(@$rvalues[$i])>0) {
625 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
626 # warn "2=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
629 $prevtag= @$rtags[$i];
633 # the last has not been included inside the loop... do it now !
635 #warn Dumper($field->{_subfields});
636 $record->add_fields($field) if (($field) && $field ne "");
637 #warn "HTML2MARC=".$record->as_formatted;
641 =head2 changeEncoding - Change the encoding of a record
645 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
647 Changes the encoding of a record
651 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
653 C<$format> - MARC or MARCXML (required)
655 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
657 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
659 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)
663 FIXME: the from_encoding doesn't work yet
665 FIXME: better handling for UNIMARC, it should allow management of 100 field
667 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
674 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
677 unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
678 unless($to_encoding) {$to_encoding = "UTF-8"};
680 # ISO-2709 Record (MARC21 or UNIMARC)
681 if (lc($format) =~ /^marc$/o) {
682 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
683 # because MARC::Record doesn't directly provide us with an encoding method
684 # It's definitely less than idea and should be fixed eventually - kados
685 my $marcxml; # temporary storage of MARCXML scalar
686 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
688 ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
692 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
694 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
696 ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
699 $error.="Unsupported record format:".$format;
701 return ($error,$newrecord);
704 =head1 INTERNAL FUNCTIONS
706 =head2 _entity_encode - Entity-encode an array of strings
710 my ($entity_encoded_string) = _entity_encode($string);
714 my (@entity_encoded_strings) = _entity_encode(@strings);
716 Entity-encode an array of strings
724 my @strings_entity_encoded;
725 foreach my $string (@strings) {
726 my $nfc_string = NFC($string);
727 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
728 push @strings_entity_encoded, $nfc_string;
730 return @strings_entity_encoded;
733 END { } # module clean-up code here (global destructor)
739 Joshua Ferraro <jmf@liblime.com>