Bug 5931 Paging and sorting saved reports table
[koha.git] / C4 / Record.pm
blobb313fb8f974345fc0c39965aa13d093776d0ed83
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 $f260 = $marc_rec_obj->field('260');
270 my $f260a = $f260->subfield('a') if $f260;
271 my $f710 = $marc_rec_obj->field('710');
272 my $f710a = $f710->subfield('a') if $f710;
273 my $f500 = $marc_rec_obj->field('500');
274 my $abstract = $f500->subfield('a') if $f500;
275 my $fields = {
276 DB => C4::Context->preference("LibraryName"),
277 Title => $marc_rec_obj->title(),
278 Author => $marc_rec_obj->author(),
279 Publisher => $f710a,
280 City => $f260a,
281 Year => $marc_rec_obj->publication_date,
282 Abstract => $abstract,
284 my $endnote;
285 my $style = new Biblio::EndnoteStyle();
286 my $template;
287 $template.= "DB - DB\n" if C4::Context->preference("LibraryName");
288 $template.="T1 - Title\n" if $marc_rec_obj->title();
289 $template.="A1 - Author\n" if $marc_rec_obj->author();
290 $template.="PB - Publisher\n" if $f710a;
291 $template.="CY - City\n" if $f260a;
292 $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
293 $template.="AB - Abstract\n" if $abstract;
294 my ($text, $errmsg) = $style->format($template, $fields);
295 return ($text);
299 =head2 marc2csv - Convert several records from UNIMARC to CSV
301 my ($csv) = marc2csv($biblios, $csvprofileid);
303 Pre and postprocessing can be done through a YAML file
305 Returns a CSV scalar
307 C<$biblio> - a list of biblionumbers
309 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)
311 =cut
313 sub marc2csv {
314 my ($biblios, $id) = @_;
315 my $output;
316 my $csv = Text::CSV::Encoded->new();
318 # Getting yaml file
319 my $configfile = "../tools/csv-profiles/$id.yaml";
320 my ($preprocess, $postprocess, $fieldprocessing);
321 if (-e $configfile){
322 ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
325 # Preprocessing
326 eval $preprocess if ($preprocess);
328 my $firstpass = 1;
329 foreach my $biblio (@$biblios) {
330 $output .= marcrecord2csv($biblio, $id, $firstpass, $csv, $fieldprocessing) ;
331 $firstpass = 0;
334 # Postprocessing
335 eval $postprocess if ($postprocess);
337 return $output;
340 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
342 my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
344 Returns a CSV scalar
346 C<$biblio> - a biblionumber
348 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)
350 C<$header> - true if the headers are to be printed (typically at first pass)
352 C<$csv> - an already initialised Text::CSV object
354 =cut
357 sub marcrecord2csv {
358 my ($biblio, $id, $header, $csv, $fieldprocessing) = @_;
359 my $output;
361 # Getting the record
362 my $record = GetMarcBiblio($biblio);
363 next unless $record;
364 # Getting the framework
365 my $frameworkcode = GetFrameworkCode($biblio);
367 # Getting information about the csv profile
368 my $profile = GetCsvProfile($id);
370 # Getting output encoding
371 my $encoding = $profile->{encoding} || 'utf8';
372 # Getting separators
373 my $csvseparator = $profile->{csv_separator} || ',';
374 my $fieldseparator = $profile->{field_separator} || '#';
375 my $subfieldseparator = $profile->{subfield_separator} || '|';
377 # TODO: Be more generic (in case we have to handle other protected chars or more separators)
378 if ($csvseparator eq '\t') { $csvseparator = "\t" }
379 if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
380 if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
381 if ($csvseparator eq '\n') { $csvseparator = "\n" }
382 if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
383 if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
385 $csv = $csv->encoding_out($encoding) ;
386 $csv->sep_char($csvseparator);
388 # Getting the marcfields
389 my $marcfieldslist = $profile->{marcfields};
391 # Getting the marcfields as an array
392 my @marcfieldsarray = split('\|', $marcfieldslist);
394 # Separating the marcfields from the the user-supplied headers
395 my @marcfields;
396 foreach (@marcfieldsarray) {
397 my @result = split('=', $_);
398 if (scalar(@result) == 2) {
399 push @marcfields, { header => $result[0], field => $result[1] };
400 } else {
401 push @marcfields, { field => $result[0] }
405 # If we have to insert the headers
406 if ($header) {
407 my @marcfieldsheaders;
408 my $dbh = C4::Context->dbh;
410 # For each field or subfield
411 foreach (@marcfields) {
413 my $field = $_->{field};
415 # If we have a user-supplied header, we use it
416 if (exists $_->{header}) {
417 push @marcfieldsheaders, $_->{header};
418 } else {
419 # If not, we get the matching tag name from koha
420 if (index($field, '$') > 0) {
421 my ($fieldtag, $subfieldtag) = split('\$', $field);
422 my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
423 my $sth = $dbh->prepare($query);
424 $sth->execute($fieldtag, $subfieldtag);
425 my @results = $sth->fetchrow_array();
426 push @marcfieldsheaders, $results[0];
427 } else {
428 my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
429 my $sth = $dbh->prepare($query);
430 $sth->execute($field);
431 my @results = $sth->fetchrow_array();
432 push @marcfieldsheaders, $results[0];
436 $csv->combine(@marcfieldsheaders);
437 $output = $csv->string() . "\n";
440 # For each marcfield to export
441 my @fieldstab;
442 foreach (@marcfields) {
443 my $marcfield = $_->{field};
444 # If it is a subfield
445 if (index($marcfield, '$') > 0) {
446 my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
447 my @fields = $record->field($fieldtag);
448 my @tmpfields;
450 # For each field
451 foreach my $field (@fields) {
453 # We take every matching subfield
454 my @subfields = $field->subfield($subfieldtag);
455 foreach my $subfield (@subfields) {
457 # Getting authorised value
458 my $authvalues = GetKohaAuthorisedValuesFromField($fieldtag, $subfieldtag, $frameworkcode, undef);
459 push @tmpfields, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
462 push (@fieldstab, join($subfieldseparator, @tmpfields));
463 # Or a field
464 } else {
465 my @fields = ($record->field($marcfield));
466 my $authvalues = GetKohaAuthorisedValuesFromField($marcfield, undef, $frameworkcode, undef);
468 my @valuesarray;
469 foreach (@fields) {
470 my $value;
472 # Getting authorised value
473 $value = defined $authvalues->{$_->as_string} ? $authvalues->{$_->as_string} : $_->as_string;
475 # Field processing
476 eval $fieldprocessing if ($fieldprocessing);
478 push @valuesarray, $value;
480 push (@fieldstab, join($fieldseparator, @valuesarray));
484 $csv->combine(@fieldstab);
485 $output .= $csv->string() . "\n";
487 return $output;
492 =head2 changeEncoding - Change the encoding of a record
494 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
496 Changes the encoding of a record
498 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
500 C<$format> - MARC or MARCXML (required)
502 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
504 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
506 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)
508 FIXME: the from_encoding doesn't work yet
510 FIXME: better handling for UNIMARC, it should allow management of 100 field
512 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
514 =cut
516 sub changeEncoding {
517 my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
518 my $newrecord;
519 my $error;
520 unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
521 unless($to_encoding) {$to_encoding = "UTF-8"};
523 # ISO-2709 Record (MARC21 or UNIMARC)
524 if (lc($format) =~ /^marc$/o) {
525 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
526 # because MARC::Record doesn't directly provide us with an encoding method
527 # It's definitely less than idea and should be fixed eventually - kados
528 my $marcxml; # temporary storage of MARCXML scalar
529 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
530 unless ($error) {
531 ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
534 # MARCXML Record
535 } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
536 my $marc;
537 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
538 unless ($error) {
539 ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
541 } else {
542 $error.="Unsupported record format:".$format;
544 return ($error,$newrecord);
547 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
549 my ($bibtex) = marc2bibtex($record, $id);
551 Returns a BibTex scalar
553 C<$record> - a MARC::Record object
555 C<$id> - an id for the BibTex record (might be the biblionumber)
557 =cut
560 sub marc2bibtex {
561 my ($record, $id) = @_;
562 my $tex;
564 # Authors
565 my $marcauthors = GetMarcAuthors($record,C4::Context->preference("marcflavour"));
566 my $author;
567 for my $authors ( map { map { @$_ } values %$_ } @$marcauthors ) {
568 $author .= " and " if ($author && $$authors{value});
569 $author .= $$authors{value} if ($$authors{value});
572 # Defining the conversion hash according to the marcflavour
573 my %bh;
574 if (C4::Context->preference("marcflavour") eq "UNIMARC") {
576 # FIXME, TODO : handle repeatable fields
577 # TODO : handle more types of documents
579 # Unimarc to bibtex hash
580 %bh = (
582 # Mandatory
583 author => $author,
584 title => $record->subfield("200", "a") || "",
585 editor => $record->subfield("210", "g") || "",
586 publisher => $record->subfield("210", "c") || "",
587 year => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
589 # Optional
590 volume => $record->subfield("200", "v") || "",
591 series => $record->subfield("225", "a") || "",
592 address => $record->subfield("210", "a") || "",
593 edition => $record->subfield("205", "a") || "",
594 note => $record->subfield("300", "a") || "",
595 url => $record->subfield("856", "u") || ""
597 } else {
599 # Marc21 to bibtex hash
600 %bh = (
602 # Mandatory
603 author => $author,
604 title => $record->subfield("245", "a") || "",
605 editor => $record->subfield("260", "f") || "",
606 publisher => $record->subfield("260", "b") || "",
607 year => $record->subfield("260", "c") || $record->subfield("260", "g") || "",
609 # Optional
610 # unimarc to marc21 specification says not to convert 200$v to marc21
611 series => $record->subfield("490", "a") || "",
612 address => $record->subfield("260", "a") || "",
613 edition => $record->subfield("250", "a") || "",
614 note => $record->subfield("500", "a") || "",
615 url => $record->subfield("856", "u") || ""
619 $tex .= "\@book{";
620 $tex .= join(",\n", $id, map { $bh{$_} ? qq(\t$_ = "$bh{$_}") : () } keys %bh);
621 $tex .= "\n}\n";
623 return $tex;
627 =head1 INTERNAL FUNCTIONS
629 =head2 _entity_encode - Entity-encode an array of strings
631 my ($entity_encoded_string) = _entity_encode($string);
635 my (@entity_encoded_strings) = _entity_encode(@strings);
637 Entity-encode an array of strings
639 =cut
641 sub _entity_encode {
642 my @strings = @_;
643 my @strings_entity_encoded;
644 foreach my $string (@strings) {
645 my $nfc_string = NFC($string);
646 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
647 push @strings_entity_encoded, $nfc_string;
649 return @strings_entity_encoded;
652 END { } # module clean-up code here (global destructor)
654 __END__
656 =head1 AUTHOR
658 Joshua Ferraro <jmf@liblime.com>
660 =head1 MODIFICATIONS
663 =cut