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