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
23 use strict;# use warnings; #FIXME: turn off warnings before release
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 Unicode::Normalize; # _entity_encode
33 use vars qw($VERSION @ISA @EXPORT);
35 # set the version for version checking
36 $VERSION = do { my @v = '$Revision$' =~ /\d+/g;
37 shift(@v) . "." . join("_", map {sprintf "%03d", $_ } @v); };
41 # only export API methods
57 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
61 New in Koha 3.x. This module handles all record-related management functions.
63 =head1 API (EXPORTED FUNCTIONS)
65 =head2 marc2marc - Convert from one flavour of ISO-2709 to another
69 my ($error,$newmarc) = marc2marc($marc,$to_flavour,$from_flavour,$encoding);
71 Returns an ISO-2709 scalar
78 my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
79 my $error = "Feature not yet implemented\n";
80 return ($error,$marc);
83 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
87 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
89 Returns a MARCXML scalar
93 C<$marc> - an ISO-2709 scalar or MARC::Record object
95 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
97 C<$flavour> - MARC21 or UNIMARC
99 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
108 my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
109 my $error; # the error string
110 my $marcxml; # the final MARCXML scalar
112 # test if it's already a MARC::Record object, if not, make it one
114 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
115 $marc_record_obj = $marc;
116 } else { # it's not a MARC::Record object, make it one
117 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
119 # conversion to MARC::Record object failed, populate $error
120 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
122 # only proceed if no errors so far
125 # check the record for warnings
126 my @warnings = $marc_record_obj->warnings();
128 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
129 foreach my $warn (@warnings) { warn "\t".$warn };
131 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
132 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour
134 # attempt to convert the record to MARCXML
135 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
137 # record creation failed, populate $error
139 $error .= "Creation of MARCXML failed:".$MARC::File::ERROR;
140 $error .= "Additional information:\n";
141 my @warnings = $@->warnings();
142 foreach my $warn (@warnings) { $error.=$warn."\n" };
144 # record creation was successful
147 # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block
148 @warnings = $marc_record_obj->warnings();
150 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
151 foreach my $warn (@warnings) { warn "\t".$warn };
155 # only proceed if no errors so far
158 # entity encode the XML unless instructed not to
159 unless ($dont_entity_encode) {
160 my ($marcxml_entity_encoded) = _entity_encode($marcxml);
161 $marcxml = $marcxml_entity_encoded;
165 # return result to calling program
166 return ($error,$marcxml);
169 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
173 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
175 Returns an ISO-2709 scalar
179 C<$marcxml> - a MARCXML record
181 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
183 C<$flavour> - MARC21 or UNIMARC
192 my ($marcxml,$encoding,$flavour) = @_;
193 my $error; # the error string
194 my $marc; # the final ISO-2709 scalar
195 unless($encoding) {$encoding = "UTF-8"}; # set the default encoding
196 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set the default MARC flavour
198 # attempt to do the conversion
199 eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
201 # record creation failed, populate $error
202 if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@;
203 $error.=$MARC::File::ERROR if ($MARC::File::ERROR);
205 # return result to calling program
206 return ($error,$marc);
209 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
213 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
215 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
217 FIXME: should return actual XML, not just an object
221 C<$marc> - an ISO-2709 scalar or MARC::Record object
223 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
232 my ($marc,$qualified) = @_;
234 # test if it's already a MARC::Record object, if not, make it one
236 if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
237 $marc_record_obj = $marc;
238 } else { # it's not a MARC::Record object, make it one
239 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
241 # conversion to MARC::Record object failed, populate $error
243 $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR;
246 my $crosswalk = MARC::Crosswalk::DublinCore->new;
248 $crosswalk = MARC::Crosswalk::DublinCore->new( qualified => 1 );
250 my $dcxml = $crosswalk->as_dublincore($marc_record_obj);
251 my $dcxmlfinal = "<?xml version=\"1.0\"?>\n";
252 $dcxmlfinal .= "<metadata
253 xmlns=\"http://example.org/myapp/\"
254 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
255 xsi:schemaLocation=\"http://example.org/myapp/ http://example.org/myapp/schema.xsd\"
256 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
257 xmlns:dcterms=\"http://purl.org/dc/terms/\">";
259 foreach my $element ( $dcxml->elements() ) {
260 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name()."\n";
262 $dcxmlfinal .= "\n</metadata>";
263 return ($error,$dcxmlfinal);
265 =head2 marc2modsxml - Convert from ISO-2709 to MODS
269 my ($error,$modsxml) = marc2modsxml($marc);
271 Returns a MODS scalar
279 # grab the XML, run it through our stylesheet, push it out to the browser
280 my $xmlrecord = marc2marcxml($marc);
281 my $xslfile = C4::Context->config('intranetdir')."/koha-tmpl/intranet-tmpl/prog/en/xslt/MARC21slim2MODS3-1.xsl";
282 my $parser = XML::LibXML->new();
283 my $xslt = XML::LibXSLT->new();
284 my $source = $parser->parse_string($xmlrecord);
285 my $style_doc = $parser->parse_file($xslfile);
286 my $stylesheet = $xslt->parse_stylesheet($style_doc);
287 my $results = $stylesheet->transform($source);
288 my $newxmlrecord = $stylesheet->output_string($results);
289 return ($newxmlrecord);
295 my ($error,$marcxml) = html2marcxml($tags,$subfields,$values,$indicator,$ind_tag);
297 Returns a MARCXML scalar
299 this is used in addbiblio.pl and additem.pl to build the MARCXML record from
302 FIXME: this could use some better code documentation
309 my ($tags,$subfields,$values,$indicator,$ind_tag) = @_;
311 # add the header info
312 my $marcxml= MARC::File::XML::header(C4::Context->preference('TemplateEncoding'),C4::Context->preference('marcflavour'));
314 # some flags used to figure out where in the record we are
320 # handle characters that would cause the parser to choke FIXME: is there a more elegant solution?
321 for (my $i=0;$i<=@$tags;$i++){
322 @$values[$i] =~ s/&/&/g;
323 @$values[$i] =~ s/</</g;
324 @$values[$i] =~ s/>/>/g;
325 @$values[$i] =~ s/"/"/g;
326 @$values[$i] =~ s/'/'/g;
328 if ((@$tags[$i] ne $prevtag)){
329 $j++ unless (@$tags[$i] eq "");
330 #warn "IND:".substr(@$indicator[$j],0,1).substr(@$indicator[$j],1,1)." ".@$tags[$i];
332 $marcxml.="</datafield>\n";
333 if ((@$tags[$i] > 10) && (@$values[$i] ne "")){
334 my $ind1 = substr(@$indicator[$j],0,1);
335 my $ind2 = substr(@$indicator[$j],1,1);
336 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
337 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
343 if (@$values[$i] ne "") {
345 if (@$tags[$i] eq "000") {
346 $marcxml.="<leader>@$values[$i]</leader>\n";
348 # rest of the fixed fields
349 } elsif (@$tags[$i] < 010) { #FIXME: <10 was the way it was, there might even be a better way
350 $marcxml.="<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
353 my $ind1 = substr(@$indicator[$j],0,1);
354 my $ind2 = substr(@$indicator[$j],1,1);
355 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
356 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
361 } else { # @$tags[$i] eq $prevtag
362 if (@$values[$i] eq "") {
365 my $ind1 = substr(@$indicator[$j],0,1);
366 my $ind2 = substr(@$indicator[$j],1,1);
367 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
370 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
373 $prevtag = @$tags[$i];
375 $marcxml.= MARC::File::XML::footer();
377 return ($error,$marcxml);
384 Probably best to avoid using this ... it has some rather striking problems:
388 * saves blank subfields
390 * subfield order is hardcoded to always start with 'a' for repeatable tags (because it is hardcoded in the addfield routine).
392 * 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).
394 * the underlying routines didn't support subfield reordering or subfield repeatability.
398 I've left it in here because it could be useful if someone took the time to fix it. -- kados
405 my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
407 my $record = MARC::Record->new();
408 # my %subfieldlist=();
409 my $prevvalue; # if tag <10
410 my $field; # if tag >=10
411 for (my $i=0; $i< @$rtags; $i++) {
412 # rebuild MARC::Record
413 # warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
414 if (@$rtags[$i] ne $prevtag) {
417 if (($prevtag ne '000') && ($prevvalue ne "")) {
418 $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
419 } elsif ($prevvalue ne ""){
420 $record->leader($prevvalue);
424 if (($field) && ($field ne "")) {
425 $record->add_fields($field);
428 $indicators{@$rtags[$i]}.=' ';
429 # skip blank tags, I hope this works
430 if (@$rtags[$i] eq ''){
431 $prevtag = @$rtags[$i];
435 if (@$rtags[$i] <10) {
436 $prevvalue= @$rvalues[$i];
440 if (@$rvalues[$i] eq "") {
443 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
445 # warn "1=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
447 $prevtag = @$rtags[$i];
449 if (@$rtags[$i] <10) {
450 $prevvalue=@$rvalues[$i];
452 if (length(@$rvalues[$i])>0) {
453 $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
454 # warn "2=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
457 $prevtag= @$rtags[$i];
461 # the last has not been included inside the loop... do it now !
463 #warn Dumper($field->{_subfields});
464 $record->add_fields($field) if (($field) && $field ne "");
465 #warn "HTML2MARC=".$record->as_formatted;
469 =head2 changeEncoding - Change the encoding of a record
473 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
475 Changes the encoding of a record
479 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
481 C<$format> - MARC or MARCXML (required)
483 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
485 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
487 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)
491 FIXME: the from_encoding doesn't work yet
493 FIXME: better handling for UNIMARC, it should allow management of 100 field
495 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
502 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
505 unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
506 unless($to_encoding) {$to_encoding = "UTF-8"};
508 # ISO-2709 Record (MARC21 or UNIMARC)
509 if (lc($format) =~ /^marc$/o) {
510 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
511 # because MARC::Record doesn't directly provide us with an encoding method
512 # It's definitely less than idea and should be fixed eventually - kados
513 my $marcxml; # temporary storage of MARCXML scalar
514 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
516 ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
520 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
522 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
524 ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
527 $error.="Unsupported record format:".$format;
529 return ($error,$newrecord);
532 =head1 INTERNAL FUNCTIONS
534 =head2 _entity_encode - Entity-encode an array of strings
538 my ($entity_encoded_string) = _entity_encode($string);
542 my (@entity_encoded_strings) = _entity_encode(@strings);
544 Entity-encode an array of strings
552 my @strings_entity_encoded;
553 foreach my $string (@strings) {
554 my $nfc_string = NFC($string);
555 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
556 push @strings_entity_encoded, $nfc_string;
558 return @strings_entity_encoded;
561 END { } # module clean-up code here (global destructor)
567 Joshua Ferraro <jmf@liblime.com>