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