Final batch of POD cleanups.
[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     warn $fieldprocessing;
328     # Preprocessing
329     eval $preprocess if ($preprocess);
330
331     my $firstpass = 1;
332     foreach my $biblio (@$biblios) {
333         $output .= marcrecord2csv($biblio, $id, $firstpass, $csv, $fieldprocessing) ;
334         $firstpass = 0;
335     }
336
337     # Postprocessing
338     eval $postprocess if ($postprocess);
339
340     return $output;
341 }
342
343 =head2 marcrecord2csv - Convert a single record from UNIMARC to CSV
344
345   my ($csv) = marcrecord2csv($biblio, $csvprofileid, $header);
346
347 Returns a CSV scalar
348
349 C<$biblio> - a biblionumber
350
351 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)
352
353 C<$header> - true if the headers are to be printed (typically at first pass)
354
355 C<$csv> - an already initialised Text::CSV object
356
357 =cut
358
359
360 sub marcrecord2csv {
361     my ($biblio, $id, $header, $csv, $fieldprocessing) = @_;
362     my $output;
363
364     # Getting the record
365     my $record = GetMarcBiblio($biblio);
366
367     # Getting the framework
368     my $frameworkcode = GetFrameworkCode($biblio);
369
370     # Getting information about the csv profile
371     my $profile = GetCsvProfile($id);
372
373     # Getting output encoding
374     my $encoding          = $profile->{encoding} || 'utf8';
375     # Getting separators
376     my $csvseparator      = $profile->{csv_separator}      || ',';
377     my $fieldseparator    = $profile->{field_separator}    || '#';
378     my $subfieldseparator = $profile->{subfield_separator} || '|';
379
380     # TODO: Be more generic (in case we have to handle other protected chars or more separators)
381     if ($csvseparator eq '\t') { $csvseparator = "\t" }
382     if ($fieldseparator eq '\t') { $fieldseparator = "\t" }
383     if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" }
384     if ($csvseparator eq '\n') { $csvseparator = "\n" }
385     if ($fieldseparator eq '\n') { $fieldseparator = "\n" }
386     if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" }
387
388     $csv = $csv->encoding_out($encoding) ;
389     $csv->sep_char($csvseparator);
390
391     # Getting the marcfields
392     my $marcfieldslist = $profile->{marcfields};
393
394     # Getting the marcfields as an array
395     my @marcfieldsarray = split('\|', $marcfieldslist);
396
397    # Separating the marcfields from the the user-supplied headers
398     my @marcfields;
399     foreach (@marcfieldsarray) {
400         my @result = split('=', $_);
401         if (scalar(@result) == 2) {
402            push @marcfields, { header => $result[0], field => $result[1] }; 
403         } else {
404            push @marcfields, { field => $result[0] }
405         }
406     }
407
408     # If we have to insert the headers
409     if ($header) {
410         my @marcfieldsheaders;
411         my $dbh   = C4::Context->dbh;
412
413         # For each field or subfield
414         foreach (@marcfields) {
415
416             my $field = $_->{field};
417
418             # If we have a user-supplied header, we use it
419             if (exists $_->{header}) {
420                     push @marcfieldsheaders, $_->{header};
421             } else {
422                 # If not, we get the matching tag name from koha
423                 if (index($field, '$') > 0) {
424                     my ($fieldtag, $subfieldtag) = split('\$', $field);
425                     my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?";
426                     my $sth = $dbh->prepare($query);
427                     $sth->execute($fieldtag, $subfieldtag);
428                     my @results = $sth->fetchrow_array();
429                     push @marcfieldsheaders, $results[0];
430                 } else {
431                     my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?";
432                     my $sth = $dbh->prepare($query);
433                     $sth->execute($field);
434                     my @results = $sth->fetchrow_array();
435                     push @marcfieldsheaders, $results[0];
436                 }
437             }
438         }
439         $csv->combine(@marcfieldsheaders);
440         $output = $csv->string() . "\n";        
441     }
442
443     # For each marcfield to export
444     my @fieldstab;
445     foreach (@marcfields) {
446         my $marcfield = $_->{field};
447         # If it is a subfield
448         if (index($marcfield, '$') > 0) {
449             my ($fieldtag, $subfieldtag) = split('\$', $marcfield);
450             my @fields = $record->field($fieldtag);
451             my @tmpfields;
452
453             # For each field
454             foreach my $field (@fields) {
455
456                 # We take every matching subfield
457                 my @subfields = $field->subfield($subfieldtag);
458                 foreach my $subfield (@subfields) {
459
460                     # Getting authorised value
461                     my $authvalues = GetKohaAuthorisedValuesFromField($fieldtag, $subfieldtag, $frameworkcode, undef);
462                     push @tmpfields, (defined $authvalues->{$subfield}) ? $authvalues->{$subfield} : $subfield;
463                 }
464             }
465             push (@fieldstab, join($subfieldseparator, @tmpfields));            
466         # Or a field
467         } else {
468             my @fields = ($record->field($marcfield));
469             my $authvalues = GetKohaAuthorisedValuesFromField($marcfield, undef, $frameworkcode, undef);
470
471             my @valuesarray;
472             foreach (@fields) {
473                 my $value;
474
475                 # Getting authorised value
476                 $value = defined $authvalues->{$_->as_string} ? $authvalues->{$_->as_string} : $_->as_string;
477
478                 # Field processing
479                 eval $fieldprocessing if ($fieldprocessing);
480
481                 push @valuesarray, $value;
482             }
483             push (@fieldstab, join($fieldseparator, @valuesarray)); 
484          }
485     };
486
487     $csv->combine(@fieldstab);
488     $output .= $csv->string() . "\n";
489
490     return $output;
491
492 }
493
494
495 =head2 html2marcxml
496
497   my ($error,$marcxml) = html2marcxml($tags,$subfields,$values,$indicator,$ind_tag);
498
499 Returns a MARCXML scalar
500
501 this is used in addbiblio.pl and additem.pl to build the MARCXML record from 
502 the form submission.
503
504 FIXME: this could use some better code documentation
505
506 =cut
507
508 sub html2marcxml {
509     my ($tags,$subfields,$values,$indicator,$ind_tag) = @_;
510         my $error;
511         # add the header info
512     my $marcxml= MARC::File::XML::header(C4::Context->preference('TemplateEncoding'),C4::Context->preference('marcflavour'));
513
514         # some flags used to figure out where in the record we are
515     my $prevvalue;
516     my $prevtag=-1;
517     my $first=1;
518     my $j = -1;
519
520         # handle characters that would cause the parser to choke FIXME: is there a more elegant solution?
521     for (my $i=0;$i<=@$tags;$i++){
522                 @$values[$i] =~ s/&/&amp;/g;
523                 @$values[$i] =~ s/</&lt;/g;
524                 @$values[$i] =~ s/>/&gt;/g;
525                 @$values[$i] =~ s/"/&quot;/g;
526                 @$values[$i] =~ s/'/&apos;/g;
527         
528                 if ((@$tags[$i] ne $prevtag)){
529                         $j++ unless (@$tags[$i] eq "");
530                         #warn "IND:".substr(@$indicator[$j],0,1).substr(@$indicator[$j],1,1)." ".@$tags[$i];
531                         if (!$first){
532                                 $marcxml.="</datafield>\n";
533                                 if ((@$tags[$i] > 10) && (@$values[$i] ne "")){
534                         my $ind1 = substr(@$indicator[$j],0,1);
535                                         my $ind2 = substr(@$indicator[$j],1,1);
536                                         $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
537                                         $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
538                                         $first=0;
539                                 } else {
540                                         $first=1;
541                                 }
542                         } else {
543                                 if (@$values[$i] ne "") {
544                                         # handle the leader
545                                         if (@$tags[$i] eq "000") {
546                                                 $marcxml.="<leader>@$values[$i]</leader>\n";
547                                                 $first=1;
548                                         # rest of the fixed fields
549                                         } elsif (@$tags[$i] lt '010') { # don't compare numerically 010 == 8
550                                                 $marcxml.="<controlfield tag=\"@$tags[$i]\">@$values[$i]</controlfield>\n";
551                                                 $first=1;
552                                         } else {
553                                                 my $ind1 = substr(@$indicator[$j],0,1);
554                                                 my $ind2 = substr(@$indicator[$j],1,1);
555                                                 $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
556                                                 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
557                                                 $first=0;
558                                         }
559                                 }
560                         }
561                 } else { # @$tags[$i] eq $prevtag
562                         if (@$values[$i] eq "") {
563                         } else {
564                                 if ($first){
565                                         my $ind1 = substr(@$indicator[$j],0,1);
566                                         my $ind2 = substr(@$indicator[$j],1,1);
567                                         $marcxml.="<datafield tag=\"@$tags[$i]\" ind1=\"$ind1\" ind2=\"$ind2\">\n";
568                                         $first=0;
569                                 }
570                                 $marcxml.="<subfield code=\"@$subfields[$i]\">@$values[$i]</subfield>\n";
571                         }
572                 }
573                 $prevtag = @$tags[$i];
574         }
575         $marcxml.= MARC::File::XML::footer();
576         #warn $marcxml;
577         return ($error,$marcxml);
578 }
579
580 =head2 html2marc
581
582 Probably best to avoid using this ... it has some rather striking problems:
583
584 * saves blank subfields
585
586 * subfield order is hardcoded to always start with 'a' for repeatable tags (because it is hardcoded in the addfield routine).
587
588 * 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).
589
590 * the underlying routines didn't support subfield reordering or subfield repeatability.
591
592 I've left it in here because it could be useful if someone took the time to fix it. -- kados
593
594 =cut
595
596 sub html2marc {
597     my ($dbh,$rtags,$rsubfields,$rvalues,%indicators) = @_;
598     my $prevtag = -1;
599     my $record = MARC::Record->new();
600 #   my %subfieldlist=();
601     my $prevvalue; # if tag <10
602     my $field; # if tag >=10
603     for (my $i=0; $i< @$rtags; $i++) {
604         # rebuild MARC::Record
605 #           warn "0=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ";
606         if (@$rtags[$i] ne $prevtag) {
607             if ($prevtag < 10) {
608                 if ($prevvalue) {
609                     if (($prevtag ne '000') && ($prevvalue ne "")) {
610                         $record->add_fields((sprintf "%03s",$prevtag),$prevvalue);
611                     } elsif ($prevvalue ne ""){
612                         $record->leader($prevvalue);
613                     }
614                 }
615             } else {
616                 if (($field) && ($field ne "")) {
617                     $record->add_fields($field);
618                 }
619             }
620             $indicators{@$rtags[$i]}.='  ';
621                 # skip blank tags, I hope this works
622                 if (@$rtags[$i] eq ''){
623                 $prevtag = @$rtags[$i];
624                 undef $field;
625                 next;
626             }
627             if (@$rtags[$i] <10) {
628                 $prevvalue= @$rvalues[$i];
629                 undef $field;
630             } else {
631                 undef $prevvalue;
632                 if (@$rvalues[$i] eq "") {
633                 undef $field;
634                 } else {
635                 $field = MARC::Field->new( (sprintf "%03s",@$rtags[$i]), substr($indicators{@$rtags[$i]},0,1),substr($indicators{@$rtags[$i]},1,1), @$rsubfields[$i] => @$rvalues[$i]);
636                 }
637 #           warn "1=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
638             }
639             $prevtag = @$rtags[$i];
640         } else {
641             if (@$rtags[$i] <10) {
642                 $prevvalue=@$rvalues[$i];
643             } else {
644                 if (length(@$rvalues[$i])>0) {
645                     $field->add_subfields(@$rsubfields[$i] => @$rvalues[$i]);
646 #           warn "2=>".@$rtags[$i].@$rsubfields[$i]." = ".@$rvalues[$i].": ".$field->as_formatted;
647                 }
648             }
649             $prevtag= @$rtags[$i];
650         }
651     }
652     #}
653     # the last has not been included inside the loop... do it now !
654     #use Data::Dumper;
655     #warn Dumper($field->{_subfields});
656     $record->add_fields($field) if (($field) && $field ne "");
657     #warn "HTML2MARC=".$record->as_formatted;
658     return $record;
659 }
660
661 =head2 changeEncoding - Change the encoding of a record
662
663   my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding);
664
665 Changes the encoding of a record
666
667 C<$record> - the record itself can be in ISO-2709, a MARC::Record object, or MARCXML for now (required)
668
669 C<$format> - MARC or MARCXML (required)
670
671 C<$flavour> - MARC21 or UNIMARC, if MARC21, it will change the leader (optional) [defaults to Koha system preference]
672
673 C<$to_encoding> - the encoding you want the record to end up in (optional) [UTF-8]
674
675 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)
676
677 FIXME: the from_encoding doesn't work yet
678
679 FIXME: better handling for UNIMARC, it should allow management of 100 field
680
681 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
682
683 =cut
684
685 sub changeEncoding {
686         my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_;
687         my $newrecord;
688         my $error;
689         unless($flavour) {$flavour = C4::Context->preference("marcflavour")};
690         unless($to_encoding) {$to_encoding = "UTF-8"};
691         
692         # ISO-2709 Record (MARC21 or UNIMARC)
693         if (lc($format) =~ /^marc$/o) {
694                 # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML
695                 #       because MARC::Record doesn't directly provide us with an encoding method
696                 #       It's definitely less than idea and should be fixed eventually - kados
697                 my $marcxml; # temporary storage of MARCXML scalar
698                 ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour);
699                 unless ($error) {
700                         ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour);
701                 }
702         
703         # MARCXML Record
704         } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record
705                 my $marc;
706                 ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour);
707                 unless ($error) {
708                         ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour);
709                 }
710         } else {
711                 $error.="Unsupported record format:".$format;
712         }
713         return ($error,$newrecord);
714 }
715
716 =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex
717
718   my ($bibtex) = marc2bibtex($record, $id);
719
720 Returns a BibTex scalar
721
722 C<$record> - a MARC::Record object
723
724 C<$id> - an id for the BibTex record (might be the biblionumber)
725
726 =cut
727
728
729 sub marc2bibtex {
730     my ($record, $id) = @_;
731     my $tex;
732
733     # Authors
734     my $marcauthors = GetMarcAuthors($record,C4::Context->preference("marcflavour"));
735     my $author;
736     for my $authors ( map { map { @$_ } values %$_  } @$marcauthors  ) {  
737         $author .= " and " if ($author && $$authors{value});
738         $author .= $$authors{value} if ($$authors{value}); 
739     }
740
741     # Defining the conversion hash according to the marcflavour
742     my %bh;
743     if (C4::Context->preference("marcflavour") eq "UNIMARC") {
744         
745         # FIXME, TODO : handle repeatable fields
746         # TODO : handle more types of documents
747
748         # Unimarc to bibtex hash
749         %bh = (
750
751             # Mandatory
752             author    => $author,
753             title     => $record->subfield("200", "a") || "",
754             editor    => $record->subfield("210", "g") || "",
755             publisher => $record->subfield("210", "c") || "",
756             year      => $record->subfield("210", "d") || $record->subfield("210", "h") || "",
757
758             # Optional
759             volume  =>  $record->subfield("200", "v") || "",
760             series  =>  $record->subfield("225", "a") || "",
761             address =>  $record->subfield("210", "a") || "",
762             edition =>  $record->subfield("205", "a") || "",
763             note    =>  $record->subfield("300", "a") || "",
764             url     =>  $record->subfield("856", "u") || ""
765         );
766     } else {
767
768         # Marc21 to bibtex hash
769         %bh = (
770
771             # Mandatory
772             author    => $author,
773             title     => $record->subfield("245", "a") || "",
774             editor    => $record->subfield("260", "f") || "",
775             publisher => $record->subfield("260", "b") || "",
776             year      => $record->subfield("260", "c") || $record->subfield("260", "g") || "",
777
778             # Optional
779             # unimarc to marc21 specification says not to convert 200$v to marc21
780             series  =>  $record->subfield("490", "a") || "",
781             address =>  $record->subfield("260", "a") || "",
782             edition =>  $record->subfield("250", "a") || "",
783             note    =>  $record->subfield("500", "a") || "",
784             url     =>  $record->subfield("856", "u") || ""
785         );
786     }
787
788     $tex .= "\@book{";
789     $tex .= join(",\n", $id, map { $bh{$_} ? qq(\t$_ = "$bh{$_}") : () } keys %bh);
790     $tex .= "\n}\n";
791
792     return $tex;
793 }
794
795
796 =head1 INTERNAL FUNCTIONS
797
798 =head2 _entity_encode - Entity-encode an array of strings
799
800   my ($entity_encoded_string) = _entity_encode($string);
801
802 or
803
804   my (@entity_encoded_strings) = _entity_encode(@strings);
805
806 Entity-encode an array of strings
807
808 =cut
809
810 sub _entity_encode {
811         my @strings = @_;
812         my @strings_entity_encoded;
813         foreach my $string (@strings) {
814                 my $nfc_string = NFC($string);
815                 $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
816                 push @strings_entity_encoded, $nfc_string;
817         }
818         return @strings_entity_encoded;
819 }
820
821 END { }       # module clean-up code here (global destructor)
822 1;
823 __END__
824
825 =head1 AUTHOR
826
827 Joshua Ferraro <jmf@liblime.com>
828
829 =head1 MODIFICATIONS
830
831
832 =cut