bug 3651 followup: updated for new GetMember() parameter style
[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 use C4::Biblio; #marc2bibtex
33 use C4::Csv; #marc2csv
34 use C4::Koha; #marc2csv
35 use YAML; #marcrecords2csv
36 use Text::CSV::Encoded; #marc2csv
37
38 use vars qw($VERSION @ISA @EXPORT);
39
40 # set the version for version checking
41 $VERSION = 3.00;
42
43 @ISA = qw(Exporter);
44
45 # only export API methods
46
47 @EXPORT = qw(
48   &marc2endnote
49   &marc2marc
50   &marc2marcxml
51   &marcxml2marc
52   &marc2dcxml
53   &marc2modsxml
54   &marc2bibtex
55   &marc2csv
56   &html2marcxml
57   &html2marc
58   &changeEncoding
59 );
60
61 =head1 NAME
62
63 C4::Record - MARC, MARCXML, DC, MODS, XML, etc. Record Management Functions and API
64
65 =head1 SYNOPSIS
66
67 New in Koha 3.x. This module handles all record-related management functions.
68
69 =head1 API (EXPORTED FUNCTIONS)
70
71 =head2 marc2marc - Convert from one flavour of ISO-2709 to another
72
73 =over 4
74
75 my ($error,$newmarc) = marc2marc($marc,$to_flavour,$from_flavour,$encoding);
76
77 Returns an ISO-2709 scalar
78
79 =back
80
81 =cut
82
83 sub marc2marc {
84         my ($marc,$to_flavour,$from_flavour,$encoding) = @_;
85         my $error = "Feature not yet implemented\n";
86         return ($error,$marc);
87 }
88
89 =head2 marc2marcxml - Convert from ISO-2709 to MARCXML
90
91 =over 4
92
93 my ($error,$marcxml) = marc2marcxml($marc,$encoding,$flavour);
94
95 Returns a MARCXML scalar
96
97 =over 2
98
99 C<$marc> - an ISO-2709 scalar or MARC::Record object
100
101 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
102
103 C<$flavour> - MARC21 or UNIMARC
104
105 C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode the xml before returning (optional)
106
107 =back
108
109 =back
110
111 =cut
112
113 sub marc2marcxml {
114         my ($marc,$encoding,$flavour,$dont_entity_encode) = @_;
115         my $error; # the error string
116         my $marcxml; # the final MARCXML scalar
117
118         # test if it's already a MARC::Record object, if not, make it one
119         my $marc_record_obj;
120         if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
121                 $marc_record_obj = $marc;
122         } else { # it's not a MARC::Record object, make it one
123                 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
124
125                 # conversion to MARC::Record object failed, populate $error
126                 if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR };
127         }
128         # only proceed if no errors so far
129         unless ($error) {
130
131                 # check the record for warnings
132                 my @warnings = $marc_record_obj->warnings();
133                 if (@warnings) {
134                         warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
135                         foreach my $warn (@warnings) { warn "\t".$warn };
136                 }
137                 unless($encoding) {$encoding = "UTF-8"}; # set default encoding
138                 unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour
139
140                 # attempt to convert the record to MARCXML
141                 eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions
142
143                 # record creation failed, populate $error
144                 if ($@) {
145                         $error .= "Creation of MARCXML failed:".$MARC::File::ERROR;
146                         $error .= "Additional information:\n";
147                         my @warnings = $@->warnings();
148                         foreach my $warn (@warnings) { $error.=$warn."\n" };
149
150                 # record creation was successful
151         } else {
152
153                         # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block
154                         @warnings = $marc_record_obj->warnings();
155                         if (@warnings) {
156                                 warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n";
157                                 foreach my $warn (@warnings) { warn "\t".$warn };
158                         }
159                 }
160
161                 # only proceed if no errors so far
162                 unless ($error) {
163
164                         # entity encode the XML unless instructed not to
165                 unless ($dont_entity_encode) {
166                         my ($marcxml_entity_encoded) = _entity_encode($marcxml);
167                         $marcxml = $marcxml_entity_encoded;
168                 }
169                 }
170         }
171         # return result to calling program
172         return ($error,$marcxml);
173 }
174
175 =head2 marcxml2marc - Convert from MARCXML to ISO-2709
176
177 =over 4
178
179 my ($error,$marc) = marcxml2marc($marcxml,$encoding,$flavour);
180
181 Returns an ISO-2709 scalar
182
183 =over 2
184
185 C<$marcxml> - a MARCXML record
186
187 C<$encoding> - UTF-8 or MARC-8 [UTF-8]
188
189 C<$flavour> - MARC21 or UNIMARC
190
191 =back
192
193 =back
194
195 =cut
196
197 sub marcxml2marc {
198     my ($marcxml,$encoding,$flavour) = @_;
199         my $error; # the error string
200         my $marc; # the final ISO-2709 scalar
201         unless($encoding) {$encoding = "UTF-8"}; # set the default encoding
202         unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set the default MARC flavour
203
204         # attempt to do the conversion
205         eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions
206
207         # record creation failed, populate $error
208         if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@;
209                 $error.=$MARC::File::ERROR if ($MARC::File::ERROR);
210                 };
211         # return result to calling program
212         return ($error,$marc);
213 }
214
215 =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core
216
217 =over 4
218
219 my ($error,$dcxml) = marc2dcxml($marc,$qualified);
220
221 Returns a DublinCore::Record object, will eventually return a Dublin Core scalar
222
223 FIXME: should return actual XML, not just an object
224
225 =over 2
226
227 C<$marc> - an ISO-2709 scalar or MARC::Record object
228
229 C<$qualified> - specify whether qualified Dublin Core should be used in the input or output [0]
230
231 =back
232
233 =back
234
235 =cut
236
237 sub marc2dcxml {
238         my ($marc,$qualified) = @_;
239         my $error;
240     # test if it's already a MARC::Record object, if not, make it one
241     my $marc_record_obj;
242     if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object
243         $marc_record_obj = $marc;
244     } else { # it's not a MARC::Record object, make it one
245                 eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions
246
247                 # conversion to MARC::Record object failed, populate $error
248                 if ($@) {
249                         $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR;
250                 }
251         }
252         my $crosswalk = MARC::Crosswalk::DublinCore->new;
253         if ($qualified) {
254                 $crosswalk = MARC::Crosswalk::DublinCore->new( qualified => 1 );
255         }
256         my $dcxml = $crosswalk->as_dublincore($marc_record_obj);
257         my $dcxmlfinal = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
258         $dcxmlfinal .= "<metadata
259   xmlns=\"http://example.org/myapp/\"
260   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
261   xsi:schemaLocation=\"http://example.org/myapp/ http://example.org/myapp/schema.xsd\"
262   xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
263   xmlns:dcterms=\"http://purl.org/dc/terms/\">";
264
265         foreach my $element ( $dcxml->elements() ) {
266                 $dcxmlfinal.="<"."dc:".$element->name().">".$element->content()."</"."dc:".$element->name().">\n";
267     }
268         $dcxmlfinal .= "\n</metadata>";
269         return ($error,$dcxmlfinal);
270 }
271 =head2 marc2modsxml - Convert from ISO-2709 to MODS
272
273 =over 4
274
275 my ($error,$modsxml) = marc2modsxml($marc);
276
277 Returns a MODS scalar
278
279 =back
280
281 =cut
282
283 sub marc2modsxml {
284         my ($marc) = @_;
285         # grab the XML, run it through our stylesheet, push it out to the browser
286         my $xmlrecord = marc2marcxml($marc);
287         my $xslfile = C4::Context->config('intrahtdocs')."/prog/en/xslt/MARC21slim2MODS3-1.xsl";
288         my $parser = XML::LibXML->new();
289         my $xslt = XML::LibXSLT->new();
290         my $source = $parser->parse_string($xmlrecord);
291         my $style_doc = $parser->parse_file($xslfile);
292         my $stylesheet = $xslt->parse_stylesheet($style_doc);
293         my $results = $stylesheet->transform($source);
294         my $newxmlrecord = $stylesheet->output_string($results);
295         return ($newxmlrecord);
296 }
297
298 sub marc2endnote {
299     my ($marc) = @_;
300         my $marc_rec_obj =  MARC::Record->new_from_usmarc($marc);
301         my $f260 = $marc_rec_obj->field('260');
302         my $f260a = $f260->subfield('a') if $f260;
303     my $f710 = $marc_rec_obj->field('710');
304     my $f710a = $f710->subfield('a') if $f710;
305         my $f500 = $marc_rec_obj->field('500');
306         my $abstract = $f500->subfield('a') if $f500;
307         my $fields = {
308                 DB => C4::Context->preference("LibraryName"),
309                 Title => $marc_rec_obj->title(),        
310                 Author => $marc_rec_obj->author(),      
311                 Publisher => $f710a,
312                 City => $f260a,
313                 Year => $marc_rec_obj->publication_date,
314                 Abstract => $abstract,
315         };
316         my $endnote;
317         my $style = new Biblio::EndnoteStyle();
318         my $template;
319         $template.= "DB - DB\n" if C4::Context->preference("LibraryName");
320         $template.="T1 - Title\n" if $marc_rec_obj->title();
321         $template.="A1 - Author\n" if $marc_rec_obj->author();
322         $template.="PB - Publisher\n" if  $f710a;
323         $template.="CY - City\n" if $f260a;
324         $template.="Y1 - Year\n" if $marc_rec_obj->publication_date;
325         $template.="AB - Abstract\n" if $abstract;
326         my ($text, $errmsg) = $style->format($template, $fields);
327         return ($text);
328         
329 }
330
331 =head2 marc2csv - Convert several records from UNIMARC to CSV
332 Pre and postprocessing can be done through a YAML file
333
334 =over 4
335
336 my ($csv) = marc2csv($biblios, $csvprofileid);
337
338 Returns a CSV scalar
339
340 =over 2
341
342 C<$biblio> - a list of biblionumbers
343
344 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)
345
346 =back
347
348 =back
349
350 =cut
351 sub marc2csv {
352     my ($biblios, $id) = @_;
353     my $output;
354     my $csv = Text::CSV::Encoded->new();
355
356     # Getting yaml file
357     my $configfile = "../tools/csv-profiles/$id.yaml";
358     my ($preprocess, $postprocess, $fieldprocessing);
359     if (-e $configfile){
360         ($preprocess,$postprocess, $fieldprocessing) = YAML::LoadFile($configfile);
361     }
362
363     warn $fieldprocessing;
364     # Preprocessing
365     eval $preprocess if ($preprocess);
366
367     my $firstpass = 1;
368     foreach my $biblio (@$biblios) {
369         $output .= marcrecord2csv($biblio, $id, $firstpass, $csv, $fieldprocessing) ;
370         $firstpass = 0;
371     }
372
373     # Postprocessing
374     eval $postprocess if ($postprocess);
375
376     return $output;
377 }
378
379 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
380
381 =over 4
382
383 my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
384
385 Returns a CSV scalar
386
387 =over 2
388
389 C<$biblio> - a biblionumber
390
391 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)
392
393 C<$header> - true if the headers are to be printed (typically at first pass)
394
395 C<$csv> - an already initialised Text::CSV object
396
397 =back
398
399 =back
400
401 =cut
402
403
404 sub marcrecord2csv {
405     my ($biblio, $id, $header, $csv, $fieldprocessing) = @_;
406     my $output;
407
408     # Getting the record
409     my $record = GetMarcBiblio($biblio);
410
411     # Getting the framework
412     my $frameworkcode = GetFrameworkCode($biblio);
413
414     # Getting information about the csv profile
415     my $profile = GetCsvProfile($id);
416
417     # Getting output encoding
418     my $encoding          = $profile->{encoding} || 'utf8';
419     # Getting separators
420     my $csvseparator      = $profile->{csv_separator}      || ',';
421     my $fieldseparator    = $profile->{field_separator}    || '#';
422     my $subfieldseparator = $profile->{subfield_separator} || '|';
423
424     # TODO: Be more generic (in case we have to handle other protected chars or more separators)
425     if ($csvseparator eq '\t') { $csvseparator = "\t" }
426     if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
427     if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
428     if ($csvseparator eq '\n') { $csvseparator = "\n" }
429     if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
430     if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
431
432     $csv = $csv->encoding_out($encoding) ;
433     $csv->sep_char($csvseparator);
434
435     # Getting the marcfields
436     my $marcfieldslist = $profile->{marcfields};
437
438     # Getting the marcfields as an array
439     my @marcfieldsarray = split('\|', $marcfieldslist);
440
441    # Separating the marcfields from the the user-supplied headers
442     my @marcfields;
443     foreach (@marcfieldsarray) {
444         my @result = split('=', $_);
445         if (scalar(@result) == 2) {
446            push @marcfields, { header => $result[0], field => $result[1] }; 
447         } else {
448            push @marcfields, { field => $result[0] }
449         }
450     }
451
452     # If we have to insert the headers
453     if ($header) {
454         my @marcfieldsheaders;
455         my $dbh   = C4::Context->dbh;
456
457         # For each field or subfield
458         foreach (@marcfields) {
459
460             my $field = $_->{field};
461
462             # If we have a user-supplied header, we use it
463             if (exists $_->{header}) {
464                     push @marcfieldsheaders, $_->{header};
465             } else {
466                 # If not, we get the matching tag name from koha
467                 if (index($field, '$') > 0) {
468                     my ($fieldtag, $subfieldtag) = split('\$', $field);
469                     my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
470                     my $sth = $dbh->prepare($query);
471                     $sth->execute($fieldtag, $subfieldtag);
472                     my @results = $sth->fetchrow_array();
473                     push @marcfieldsheaders, $results[0];
474                 } else {
475                     my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
476                     my $sth = $dbh->prepare($query);
477                     $sth->execute($field);
478                     my @results = $sth->fetchrow_array();
479                     push @marcfieldsheaders, $results[0];
480                 }
481             }
482         }
483         $csv->combine(@marcfieldsheaders);
484         $output = $csv->string() . "\n";        
485     }
486
487     # For each marcfield to export
488     my @fieldstab;
489     foreach (@marcfields) {
490         my $marcfield = $_->{field};
491         # If it is a subfield
492         if (index($marcfield, '$') > 0) {
493             my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
494             my @fields = $record->field($fieldtag);
495             my @tmpfields;
496
497             # For each field
498             foreach my $field (@fields) {
499
500                 # We take every matching subfield
501                 my @subfields = $field->subfield($subfieldtag);
502                 foreach my $subfield (@subfields) {
503
504                     # Getting authorised value
505                     my $authvalues = GetKohaAuthorisedValuesFromField($fieldtag, $subfieldtag, $frameworkcode, undef);
506                     push @tmpfields, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
507                 }
508             }
509             push (@fieldstab, join($subfieldseparator, @tmpfields));            
510         # Or a field
511         } else {
512             my @fields = ($record->field($marcfield));
513             my $authvalues = GetKohaAuthorisedValuesFromField($marcfield, undef, $frameworkcode, undef);
514
515             my @valuesarray;
516             foreach (@fields) {
517                 my $value;
518
519                 # Getting authorised value
520                 $value = defined $authvalues->{$_->as_string} ? $authvalues->{$_->as_string} : $_->as_string;
521
522                 # Field processing
523                 eval $fieldprocessing if ($fieldprocessing);
524
525                 push @valuesarray, $value;
526             }
527             push (@fieldstab, join($fieldseparator, @valuesarray)); 
528          }
529     };
530
531     $csv->combine(@fieldstab);
532     $output .= $csv->string() . "\n";
533
534     return $output;
535
536 }
537
538
539 =head2 html2marcxml
540
541 =over 4
542
543 my ($error,$marcxml) = html2marcxml($tags,$subfields,$values,$indicator,$ind_tag);
544
545 Returns a MARCXML scalar
546
547 this is used in addbiblio.pl and additem.pl to build the MARCXML record from 
548 the form submission.
549
550 FIXME: this could use some better code documentation
551
552 =back
553
554 =cut
555
556 sub html2marcxml {
557     my ($tags,$subfields,$values,$indicator,$ind_tag) = @_;
558         my $error;
559         # add the header info
560     my $marcxml= MARC::File::XML::header(C4::Context->preference('TemplateEncoding'),C4::Context->preference('marcflavour'));
561
562         # some flags used to figure out where in the record we are
563     my $prevvalue;
564     my $prevtag=-1;
565     my $first=1;
566     my $j = -1;
567
568         # handle characters that would cause the parser to choke FIXME: is there a more elegant solution?
569     for (my $i=0;$i<=@$tags;$i++){
570                 @$values[$i] =~ s/&/&amp;/g;
571                 @$values[$i] =~ s/</&lt;/g;
572                 @$values[$i] =~ s/>/&gt;/g;
573                 @$values[$i] =~ s/"/&quot;/g;
574                 @$values[$i] =~ s/'/&apos;/g;
575         
576                 if ((@$tags[$i] ne $prevtag)){
577                         $j++ unless (@$tags[$i] eq "");
578                         #warn "IND:".substr(@$indicator[$j],0,1).substr(@$indicator[$j],1,1)." ".@$tags[$i];
579                         if (!$first){
580                                 $marcxml.="</datafield>\n";
581                                 if ((@$tags[$i] > 10) && (@$values[$i] ne "")){
582                         my $ind1 = substr(@$indicator[$j],0,1);
583                                         my $ind2 = substr(@$indicator[$j],1,1);
584                                         $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
585                                         $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
586                                         $first=0;
587                                 } else {
588                                         $first=1;
589                                 }
590                         } else {
591                                 if (@$values[$i] ne "") {
592                                         # handle the leader
593                                         if (@$tags[$i] eq "000") {
594                                                 $marcxml.="<leader>@$values[$i]</leader>\n";
595                                                 $first=1;
596                                         # rest of the fixed fields
597                                         } elsif (@$tags[$i] lt '010') { # don't compare numerically 010 == 8
598                                                 $marcxml.="<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
599                                                 $first=1;
600                                         } else {
601                                                 my $ind1 = substr(@$indicator[$j],0,1);
602                                                 my $ind2 = substr(@$indicator[$j],1,1);
603                                                 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
604                                                 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
605                                                 $first=0;
606                                         }
607                                 }
608                         }
609                 } else { # @$tags[$i] eq $prevtag
610                         if (@$values[$i] eq "") {
611                         } else {
612                                 if ($first){
613                                         my $ind1 = substr(@$indicator[$j],0,1);
614                                         my $ind2 = substr(@$indicator[$j],1,1);
615                                         $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
616                                         $first=0;
617                                 }
618                                 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
619                         }
620                 }
621                 $prevtag = @$tags[$i];
622         }
623         $marcxml.= MARC::File::XML::footer();
624         #warn $marcxml;
625         return ($error,$marcxml);
626 }
627
628 =head2 html2marc
629
630 =over 4
631
632 Probably best to avoid using this ... it has some rather striking problems:
633
634 =over 2
635
636 * saves blank subfields
637
638 * subfield order is hardcoded to always start with 'a' for repeatable tags (because it is hardcoded in the addfield routine).
639
640 * 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).
641
642 * the underlying routines didn't support subfield reordering or subfield repeatability.
643
644 =back 
645
646 I've left it in here because it could be useful if someone took the time to fix it. -- kados
647
648 =back
649
650 =cut
651
652 sub html2marc {
653     my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
654     my $prevtag = -1;
655     my $record = MARC::Record->new();
656 #   my %subfieldlist=();
657     my $prevvalue; # if tag <10
658     my $field; # if tag >=10
659     for (my $i=0; $i< @$rtags; $i++) {
660         # rebuild MARC::Record
661 #           warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
662         if (@$rtags[$i] ne $prevtag) {
663             if ($prevtag < 10) {
664                 if ($prevvalue) {
665                     if (($prevtag ne '000') && ($prevvalue ne "")) {
666                         $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
667                     } elsif ($prevvalue ne ""){
668                         $record->leader($prevvalue);
669                     }
670                 }
671             } else {
672                 if (($field) && ($field ne "")) {
673                     $record->add_fields($field);
674                 }
675             }
676             $indicators{@$rtags[$i]}.='  ';
677                 # skip blank tags, I hope this works
678                 if (@$rtags[$i] eq ''){
679                 $prevtag = @$rtags[$i];
680                 undef $field;
681                 next;
682             }
683             if (@$rtags[$i] <10) {
684                 $prevvalue= @$rvalues[$i];
685                 undef $field;
686             } else {
687                 undef $prevvalue;
688                 if (@$rvalues[$i] eq "") {
689                 undef $field;
690                 } else {
691                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
692                 }
693 #           warn "1=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
694             }
695             $prevtag = @$rtags[$i];
696         } else {
697             if (@$rtags[$i] <10) {
698                 $prevvalue=@$rvalues[$i];
699             } else {
700                 if (length(@$rvalues[$i])>0) {
701                     $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
702 #           warn "2=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
703                 }
704             }
705             $prevtag= @$rtags[$i];
706         }
707     }
708     #}
709     # the last has not been included inside the loop... do it now !
710     #use Data::Dumper;
711     #warn Dumper($field->{_subfields});
712     $record->add_fields($field) if (($field) && $field ne "");
713     #warn "HTML2MARC=".$record->as_formatted;
714     return $record;
715 }
716
717 =head2 changeEncoding - Change the encoding of a record
718
719 =over 4
720
721 my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
722
723 Changes the encoding of a record
724
725 =over 2
726
727 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
728
729 C<$format> - MARC or MARCXML (required)
730
731 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
732
733 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
734
735 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)
736
737 =back 
738
739 FIXME: the from_encoding doesn't work yet
740
741 FIXME: better handling for UNIMARC, it should allow management of 100 field
742
743 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
744
745 =back
746
747 =cut
748
749 sub changeEncoding {
750         my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
751         my $newrecord;
752         my $error;
753         unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
754         unless($to_encoding) {$to_encoding = "UTF-8"};
755         
756         # ISO-2709 Record (MARC21 or UNIMARC)
757         if (lc($format) =~ /^marc$/o) {
758                 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
759                 #       because MARC::Record doesn't directly provide us with an encoding method
760                 #       It's definitely less than idea and should be fixed eventually - kados
761                 my $marcxml; # temporary storage of MARCXML scalar
762                 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
763                 unless ($error) {
764                         ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
765                 }
766         
767         # MARCXML Record
768         } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
769                 my $marc;
770                 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
771                 unless ($error) {
772                         ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
773                 }
774         } else {
775                 $error.="Unsupported record format:".$format;
776         }
777         return ($error,$newrecord);
778 }
779
780 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
781
782 =over 4
783
784 my ($bibtex) = marc2bibtex($record, $id);
785
786 Returns a BibTex scalar
787
788 =over 2
789
790 C<$record> - a MARC::Record object
791
792 C<$id> - an id for the BibTex record (might be the biblionumber)
793
794 =back
795
796 =back
797
798 =cut
799
800
801 sub marc2bibtex {
802     my ($record, $id) = @_;
803     my $tex;
804
805     # Authors
806     my $marcauthors = GetMarcAuthors($record,C4::Context->preference("marcflavour"));
807     my $author;
808     for my $authors ( map { map { @$_ } values %$_  } @$marcauthors  ) {  
809         $author .= " and " if ($author && $$authors{value});
810         $author .= $$authors{value} if ($$authors{value}); 
811     }
812
813     # Defining the conversion hash according to the marcflavour
814     my %bh;
815     if (C4::Context->preference("marcflavour") eq "UNIMARC") {
816         
817         # FIXME, TODO : handle repeatable fields
818         # TODO : handle more types of documents
819
820         # Unimarc to bibtex hash
821         %bh = (
822
823             # Mandatory
824             author    => $author,
825             title     => $record->subfield("200", "a") || "",
826             editor    => $record->subfield("210", "g") || "",
827             publisher => $record->subfield("210", "c") || "",
828             year      => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
829
830             # Optional
831             volume  =>  $record->subfield("200", "v") || "",
832             series  =>  $record->subfield("225", "a") || "",
833             address =>  $record->subfield("210", "a") || "",
834             edition =>  $record->subfield("205", "a") || "",
835             note    =>  $record->subfield("300", "a") || "",
836             url     =>  $record->subfield("856", "u") || ""
837         );
838     } else {
839
840         # Marc21 to bibtex hash
841         %bh = (
842
843             # Mandatory
844             author    => $author,
845             title     => $record->subfield("245", "a") || "",
846             editor    => $record->subfield("260", "f") || "",
847             publisher => $record->subfield("260", "b") || "",
848             year      => $record->subfield("260", "c") || $record->subfield("260", "g") || "",
849
850             # Optional
851             # unimarc to marc21 specification says not to convert 200$v to marc21
852             series  =>  $record->subfield("490", "a") || "",
853             address =>  $record->subfield("260", "a") || "",
854             edition =>  $record->subfield("250", "a") || "",
855             note    =>  $record->subfield("500", "a") || "",
856             url     =>  $record->subfield("856", "u") || ""
857         );
858     }
859
860     $tex .= "\@book{";
861     $tex .= join(",\n", $id, map { $bh{$_} ? qq(\t$_ = "$bh{$_}") : () } keys %bh);
862     $tex .= "\n}\n";
863
864     return $tex;
865 }
866
867
868 =head1 INTERNAL FUNCTIONS
869
870 =head2 _entity_encode - Entity-encode an array of strings
871
872 =over 4
873
874 my ($entity_encoded_string) = _entity_encode($string);
875
876 or
877
878 my (@entity_encoded_strings) = _entity_encode(@strings);
879
880 Entity-encode an array of strings
881
882 =back
883
884 =cut
885
886 sub _entity_encode {
887         my @strings = @_;
888         my @strings_entity_encoded;
889         foreach my $string (@strings) {
890                 my $nfc_string = NFC($string);
891                 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
892                 push @strings_entity_encoded, $nfc_string;
893         }
894         return @strings_entity_encoded;
895 }
896
897 END { }       # module clean-up code here (global destructor)
898 1;
899 __END__
900
901 =head1 AUTHOR
902
903 Joshua Ferraro <jmf@liblime.com>
904
905 =head1 MODIFICATIONS
906
907
908 =cut