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