rename internal function
[koha.git] / C4 / Record.pm
1 package C4::Record;
2 #
3 # Copyright 2006 (C) LibLime
4 # Joshua Ferraro <jmf@liblime.com>
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
16 #
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
20 #
21 #
22 use strict;# use warnings; #FIXME: turn off warnings before release
23
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
33 use vars qw($VERSION @ISA @EXPORT);
34
35 # set the version for version checking
36 $VERSION = 3.00;
37
38 @ISA = qw(Exporter);
39
40 # only export API methods
41
42 @EXPORT = qw(
43   &marc2endnote
44   &marc2marc
45   &marc2marcxml
46   &marcxml2marc
47   &marc2dcxml
48   &marc2modsxml
49
50   &html2marcxml
51   &html2marc
52   &changeEncoding
53 );
54
55 =head1 NAME
56
57 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
58
59 =head1 SYNOPSIS
60
61 New in Koha 3.x. This module handles all record-related management functions.
62
63 =head1 API (EXPORTED FUNCTIONS)
64
65 =head2 marc2marc - Convert from one flavour of ISO-2709 to another
66
67 =over 4
68
69 my ($error,$newmarc) = marc2marc($marc,$to_flavour,$from_flavour,$encoding);
70
71 Returns an ISO-2709 scalar
72
73 =back
74
75 =cut
76
77 sub marc2marc {
78         my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
79         my $error = "Feature not yet implemented\n";
80         return ($error,$marc);
81 }
82
83 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
84
85 =over 4
86
87 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
88
89 Returns a MARCXML scalar
90
91 =over 2
92
93 C<$marc> - an ISO-2709 scalar or MARC::Record object
94
95 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
96
97 C<$flavour> - MARC21 or UNIMARC
98
99 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
100
101 =back
102
103 =back
104
105 =cut
106
107 sub marc2marcxml {
108         my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
109         my $error; # the error string
110         my $marcxml; # the final MARCXML scalar
111
112         # test if it's already a MARC::Record object, if not, make it one
113         my $marc_record_obj;
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
118
119                 # conversion to MARC::Record object failed, populate $error
120                 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
121         }
122         # only proceed if no errors so far
123         unless ($error) {
124
125                 # check the record for warnings
126                 my @warnings = $marc_record_obj->warnings();
127                 if (@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 };
130                 }
131                 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
132                 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour
133
134                 # attempt to convert the record to MARCXML
135                 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
136
137                 # record creation failed, populate $error
138                 if ($@) {
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" };
143
144                 # record creation was successful
145         } else {
146
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();
149                         if (@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 };
152                         }
153                 }
154
155                 # only proceed if no errors so far
156                 unless ($error) {
157
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;
162                 }
163                 }
164         }
165         # return result to calling program
166         return ($error,$marcxml);
167 }
168
169 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
170
171 =over 4
172
173 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
174
175 Returns an ISO-2709 scalar
176
177 =over 2
178
179 C<$marcxml> - a MARCXML record
180
181 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
182
183 C<$flavour> - MARC21 or UNIMARC
184
185 =back
186
187 =back
188
189 =cut
190
191 sub marcxml2marc {
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
197
198         # attempt to do the conversion
199         eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
200
201         # record creation failed, populate $error
202         if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@;
203                 $error.=$MARC::File::ERROR if ($MARC::File::ERROR);
204                 };
205         # return result to calling program
206         return ($error,$marc);
207 }
208
209 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
210
211 =over 4
212
213 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
214
215 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
216
217 FIXME: should return actual XML, not just an object
218
219 =over 2
220
221 C<$marc> - an ISO-2709 scalar or MARC::Record object
222
223 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
224
225 =back
226
227 =back
228
229 =cut
230
231 sub marc2dcxml {
232         my ($marc,$qualified) = @_;
233         my $error;
234     # test if it's already a MARC::Record object, if not, make it one
235     my $marc_record_obj;
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
240
241                 # conversion to MARC::Record object failed, populate $error
242                 if ($@) {
243                         $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR;
244                 }
245         }
246         my $crosswalk = MARC::Crosswalk::DublinCore->new;
247         if ($qualified) {
248                 $crosswalk = MARC::Crosswalk::DublinCore->new( qualified => 1 );
249         }
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/\">";
258
259         foreach my $element ( $dcxml->elements() ) {
260                 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name()."\n";
261     }
262         $dcxmlfinal .= "\n</metadata>";
263         return ($error,$dcxmlfinal);
264 }
265 =head2 marc2modsxml - Convert from ISO-2709 to MODS
266
267 =over 4
268
269 my ($error,$modsxml) = marc2modsxml($marc);
270
271 Returns a MODS scalar
272
273 =back
274
275 =cut
276
277 sub marc2modsxml {
278         my ($marc) = @_;
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);
290 }
291
292 sub marc2endnote {
293     my ($marc) = @_;
294         my $marc_rec_obj =  MARC::Record->new_from_usmarc($marc);
295         my $f260 = $marc_rec_obj->field('260');
296         my $f260a = $f260->subfield('a') if $f260;
297     my $f710 = $marc_rec_obj->field('710');
298     my $f710a = $f710->subfield('a') if $f710;
299         my $f500 = $marc_rec_obj->field('500');
300         my $abstract = $f500->subfield('a') if $f500;
301         my $fields = {
302                 DB => C4::Context->preference("LibraryName"),
303                 Title => $marc_rec_obj->title(),        
304                 Author => $marc_rec_obj->author(),      
305                 Publisher => $f710a,
306                 City => $f260a,
307                 Year => $marc_rec_obj->publication_date,
308                 Abstract => $abstract,
309         };
310         my $endnote;
311         my $style = new Biblio::EndnoteStyle();
312         my $template;
313         $template.= "DB - DB\n" if C4::Context->preference("LibraryName");
314         $template.="T1 - Title\n" if $marc_rec_obj->title();
315         $template.="A1 - Author\n" if $marc_rec_obj->author();
316         $template.="PB - Publisher\n" if  $f710a;
317         $template.="CY - City\n" if $f260a;
318         $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
319         $template.="AB - Abstract\n" if $abstract;
320         my ($text, $errmsg) = $style->format($template, $fields);
321         return ($text);
322         
323 }
324
325
326 =head2 html2marcxml
327
328 =over 4
329
330 my ($error,$marcxml) = html2marcxml($tags,$subfields,$values,$indicator,$ind_tag);
331
332 Returns a MARCXML scalar
333
334 this is used in addbiblio.pl and additem.pl to build the MARCXML record from 
335 the form submission.
336
337 FIXME: this could use some better code documentation
338
339 =back
340
341 =cut
342
343 sub html2marcxml {
344     my ($tags,$subfields,$values,$indicator,$ind_tag) = @_;
345         my $error;
346         # add the header info
347     my $marcxml= MARC::File::XML::header(C4::Context->preference('TemplateEncoding'),C4::Context->preference('marcflavour'));
348
349         # some flags used to figure out where in the record we are
350     my $prevvalue;
351     my $prevtag=-1;
352     my $first=1;
353     my $j = -1;
354
355         # handle characters that would cause the parser to choke FIXME: is there a more elegant solution?
356     for (my $i=0;$i<=@$tags;$i++){
357                 @$values[$i] =~ s/&/&amp;/g;
358                 @$values[$i] =~ s/</&lt;/g;
359                 @$values[$i] =~ s/>/&gt;/g;
360                 @$values[$i] =~ s/"/&quot;/g;
361                 @$values[$i] =~ s/'/&apos;/g;
362         
363                 if ((@$tags[$i] ne $prevtag)){
364                         $j++ unless (@$tags[$i] eq "");
365                         #warn "IND:".substr(@$indicator[$j],0,1).substr(@$indicator[$j],1,1)." ".@$tags[$i];
366                         if (!$first){
367                                 $marcxml.="</datafield>\n";
368                                 if ((@$tags[$i] > 10) && (@$values[$i] ne "")){
369                         my $ind1 = substr(@$indicator[$j],0,1);
370                                         my $ind2 = substr(@$indicator[$j],1,1);
371                                         $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
372                                         $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
373                                         $first=0;
374                                 } else {
375                                         $first=1;
376                                 }
377                         } else {
378                                 if (@$values[$i] ne "") {
379                                         # handle the leader
380                                         if (@$tags[$i] eq "000") {
381                                                 $marcxml.="<leader>@$values[$i]</leader>\n";
382                                                 $first=1;
383                                         # rest of the fixed fields
384                                         } elsif (@$tags[$i] < 010) { #FIXME: <10 was the way it was, there might even be a better way
385                                                 $marcxml.="<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
386                                                 $first=1;
387                                         } else {
388                                                 my $ind1 = substr(@$indicator[$j],0,1);
389                                                 my $ind2 = substr(@$indicator[$j],1,1);
390                                                 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
391                                                 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
392                                                 $first=0;
393                                         }
394                                 }
395                         }
396                 } else { # @$tags[$i] eq $prevtag
397                         if (@$values[$i] eq "") {
398                         } else {
399                                 if ($first){
400                                         my $ind1 = substr(@$indicator[$j],0,1);
401                                         my $ind2 = substr(@$indicator[$j],1,1);
402                                         $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
403                                         $first=0;
404                                 }
405                                 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
406                         }
407                 }
408                 $prevtag = @$tags[$i];
409         }
410         $marcxml.= MARC::File::XML::footer();
411         #warn $marcxml;
412         return ($error,$marcxml);
413 }
414
415 =head2 html2marc
416
417 =over 4
418
419 Probably best to avoid using this ... it has some rather striking problems:
420
421 =over 2
422
423 * saves blank subfields
424
425 * subfield order is hardcoded to always start with 'a' for repeatable tags (because it is hardcoded in the addfield routine).
426
427 * 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).
428
429 * the underlying routines didn't support subfield reordering or subfield repeatability.
430
431 =back 
432
433 I've left it in here because it could be useful if someone took the time to fix it. -- kados
434
435 =back
436
437 =cut
438
439 sub html2marc {
440     my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
441     my $prevtag = -1;
442     my $record = MARC::Record->new();
443 #   my %subfieldlist=();
444     my $prevvalue; # if tag <10
445     my $field; # if tag >=10
446     for (my $i=0; $i< @$rtags; $i++) {
447         # rebuild MARC::Record
448 #           warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
449         if (@$rtags[$i] ne $prevtag) {
450             if ($prevtag < 10) {
451                 if ($prevvalue) {
452                     if (($prevtag ne '000') && ($prevvalue ne "")) {
453                         $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
454                     } elsif ($prevvalue ne ""){
455                         $record->leader($prevvalue);
456                     }
457                 }
458             } else {
459                 if (($field) && ($field ne "")) {
460                     $record->add_fields($field);
461                 }
462             }
463             $indicators{@$rtags[$i]}.='  ';
464                 # skip blank tags, I hope this works
465                 if (@$rtags[$i] eq ''){
466                 $prevtag = @$rtags[$i];
467                 undef $field;
468                 next;
469             }
470             if (@$rtags[$i] <10) {
471                 $prevvalue= @$rvalues[$i];
472                 undef $field;
473             } else {
474                 undef $prevvalue;
475                 if (@$rvalues[$i] eq "") {
476                 undef $field;
477                 } else {
478                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
479                 }
480 #           warn "1=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
481             }
482             $prevtag = @$rtags[$i];
483         } else {
484             if (@$rtags[$i] <10) {
485                 $prevvalue=@$rvalues[$i];
486             } else {
487                 if (length(@$rvalues[$i])>0) {
488                     $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
489 #           warn "2=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
490                 }
491             }
492             $prevtag= @$rtags[$i];
493         }
494     }
495     #}
496     # the last has not been included inside the loop... do it now !
497     #use Data::Dumper;
498     #warn Dumper($field->{_subfields});
499     $record->add_fields($field) if (($field) && $field ne "");
500     #warn "HTML2MARC=".$record->as_formatted;
501     return $record;
502 }
503
504 =head2 changeEncoding - Change the encoding of a record
505
506 =over 4
507
508 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
509
510 Changes the encoding of a record
511
512 =over 2
513
514 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
515
516 C<$format> - MARC or MARCXML (required)
517
518 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
519
520 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
521
522 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)
523
524 =back 
525
526 FIXME: the from_encoding doesn't work yet
527
528 FIXME: better handling for UNIMARC, it should allow management of 100 field
529
530 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
531
532 =back
533
534 =cut
535
536 sub changeEncoding {
537         my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
538         my $newrecord;
539         my $error;
540         unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
541         unless($to_encoding) {$to_encoding = "UTF-8"};
542         
543         # ISO-2709 Record (MARC21 or UNIMARC)
544         if (lc($format) =~ /^marc$/o) {
545                 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
546                 #       because MARC::Record doesn't directly provide us with an encoding method
547                 #       It's definitely less than idea and should be fixed eventually - kados
548                 my $marcxml; # temporary storage of MARCXML scalar
549                 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
550                 unless ($error) {
551                         ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
552                 }
553         
554         # MARCXML Record
555         } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
556                 my $marc;
557                 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
558                 unless ($error) {
559                         ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
560                 }
561         } else {
562                 $error.="Unsupported record format:".$format;
563         }
564         return ($error,$newrecord);
565 }
566
567 =head1 INTERNAL FUNCTIONS
568
569 =head2 _entity_encode - Entity-encode an array of strings
570
571 =over 4
572
573 my ($entity_encoded_string) = _entity_encode($string);
574
575 or
576
577 my (@entity_encoded_strings) = _entity_encode(@strings);
578
579 Entity-encode an array of strings
580
581 =back
582
583 =cut
584
585 sub _entity_encode {
586         my @strings = @_;
587         my @strings_entity_encoded;
588         foreach my $string (@strings) {
589                 my $nfc_string = NFC($string);
590                 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
591                 push @strings_entity_encoded, $nfc_string;
592         }
593         return @strings_entity_encoded;
594 }
595
596 END { }       # module clean-up code here (global destructor)
597 1;
598 __END__
599
600 =head1 AUTHOR
601
602 Joshua Ferraro <jmf@liblime.com>
603
604 =head1 MODIFICATIONS
605
606
607 =cut