ef2a37da14436ca5de7ebbccfa1946ce5cae71eb
[koha.git] / Koha / Exporter / Record.pm
1 package Koha::Exporter::Record;
2
3 use Modern::Perl;
4 use MARC::File::XML;
5 use MARC::File::USMARC;
6
7 use C4::AuthoritiesMarc;
8 use C4::Biblio;
9 use C4::Record;
10 use Koha::CsvProfiles;
11
12 sub _get_record_for_export {
13     my ($params)           = @_;
14     my $record_type        = $params->{record_type};
15     my $record_id          = $params->{record_id};
16     my $dont_export_fields = $params->{dont_export_fields};
17     my $clean              = $params->{clean};
18
19     my $record;
20     if ( $record_type eq 'auths' ) {
21         $record = _get_authority_for_export( { %$params, authid => $record_id } );
22     } elsif ( $record_type eq 'bibs' ) {
23         $record = _get_biblio_for_export( { %$params, biblionumber => $record_id } );
24     } else {
25
26         # TODO log "record_type not supported"
27         return;
28     }
29
30     if ($dont_export_fields) {
31         for my $f ( split / /, $dont_export_fields ) {
32             if ( $f =~ m/^(\d{3})(.)?$/ ) {
33                 my ( $field, $subfield ) = ( $1, $2 );
34
35                 # skip if this record doesn't have this field
36                 if ( defined $record->field($field) ) {
37                     if ( defined $subfield ) {
38                         my @tags = $record->field($field);
39                         foreach my $t (@tags) {
40                             $t->delete_subfields($subfield);
41                         }
42                     } else {
43                         $record->delete_fields( $record->field($field) );
44                     }
45                 }
46             }
47         }
48     }
49     C4::Biblio::RemoveAllNsb($record) if $clean;
50     return $record;
51 }
52
53 sub _get_authority_for_export {
54     my ($params) = @_;
55     my $authid = $params->{authid} || return;
56     my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid);
57     return unless $authority;
58     return $authority->record;
59 }
60
61 sub _get_biblio_for_export {
62     my ($params)     = @_;
63     my $biblionumber = $params->{biblionumber};
64     my $itemnumbers  = $params->{itemnumbers};
65     my $export_items = $params->{export_items} // 1;
66     my $only_export_items_for_branch = $params->{only_export_items_for_branch};
67
68     my $record = eval { C4::Biblio::GetMarcBiblio($biblionumber); };
69
70     return if $@ or not defined $record;
71
72     if ($export_items) {
73         C4::Biblio::EmbedItemsInMarcBiblio( $record, $biblionumber, $itemnumbers );
74         if ($only_export_items_for_branch) {
75             my ( $homebranchfield, $homebranchsubfield ) = GetMarcFromKohaField( 'items.homebranch', '' );    # Should be GetFrameworkCode( $biblionumber )?
76
77             for my $itemfield ( $record->field($homebranchfield) ) {
78                 my $homebranch = $itemfield->subfield($homebranchsubfield);
79                 if ( $only_export_items_for_branch ne $homebranch ) {
80                     $record->delete_field($itemfield);
81                 }
82             }
83         }
84     }
85     return $record;
86 }
87
88 sub export {
89     my ($params) = @_;
90
91     my $record_type        = $params->{record_type};
92     my $record_ids         = $params->{record_ids} || [];
93     my $format             = $params->{format};
94     my $itemnumbers        = $params->{itemnumbers} || [];    # Does not make sense with record_type eq auths
95     my $export_items       = $params->{export_items};
96     my $dont_export_fields = $params->{dont_export_fields};
97     my $csv_profile_id     = $params->{csv_profile_id};
98     my $output_filepath    = $params->{output_filepath};
99
100     return unless $record_type;
101     return unless @$record_ids;
102
103     my $fh;
104     if ( $output_filepath ) {
105         open $fh, '>', $output_filepath or die "Cannot open file $output_filepath ($!)";
106         select $fh;
107         binmode $fh, ':encoding(UTF-8)' unless $format eq 'csv';
108     } else {
109         binmode STDOUT, ':encoding(UTF-8)' unless $format eq 'csv';
110     }
111
112     if ( $format eq 'iso2709' ) {
113         for my $record_id (@$record_ids) {
114             my $record = _get_record_for_export( { %$params, record_id => $record_id } );
115             my $errorcount_on_decode = eval { scalar( MARC::File::USMARC->decode( $record->as_usmarc )->warnings() ) };
116             if ( $errorcount_on_decode or $@ ) {
117                 warn $@ if $@;
118                 warn "record (number $record_id) is invalid and therefore not exported because its reopening generates warnings above";
119                 next;
120             }
121             print $record->as_usmarc();
122         }
123     } elsif ( $format eq 'xml' ) {
124         my $marcflavour = C4::Context->preference("marcflavour");
125         MARC::File::XML->default_record_format( ( $marcflavour eq 'UNIMARC' && $record_type eq 'auths' ) ? 'UNIMARCAUTH' : $marcflavour );
126
127         print MARC::File::XML::header();
128         print "\n";
129         for my $record_id (@$record_ids) {
130             my $record = _get_record_for_export( { %$params, record_id => $record_id } );
131             print MARC::File::XML::record($record);
132             print "\n";
133         }
134         print MARC::File::XML::footer();
135         print "\n";
136     } elsif ( $format eq 'csv' ) {
137         unless ( $csv_profile_id ) {
138             # FIXME export_format.profile should be a unique key
139             my $csv_profiles = Koha::CsvProfiles->search({ profile => C4::Context->preference('ExportWithCsvProfile') });
140             die "The ExportWithCsvProfile system preference is not defined or does not match a valid csv profile" unless $csv_profiles->count;
141             $csv_profile_id = $csv_profiles->next->export_format_id;
142         }
143         print marc2csv( $record_ids, $csv_profile_id, $itemnumbers );
144     }
145
146     close $fh if $output_filepath;
147 }
148
149 1;
150
151 __END__
152
153 =head1 NAME
154
155 Koha::Exporter::Records - module to export records (biblios and authorities)
156
157 =head1 SYNOPSIS
158
159 This module provides a public subroutine to export records as xml, csv or iso2709.
160
161 =head2 FUNCTIONS
162
163 =head3 export
164
165     Koha::Exporter::Record::export($params);
166
167 $params is a hashref with some keys:
168
169 It will displays on STDOUT the generated file.
170
171 =over 4
172
173 =item record_type
174
175   Must be set to 'bibs' or 'auths'
176
177 =item record_ids
178
179   The list of the records to export (a list of biblionumber or authid)
180
181 =item format
182
183   The format must be 'csv', 'xml' or 'iso2709'.
184
185 =item itemnumbers
186
187   Generate the item infos only for these itemnumbers.
188
189   Must only be used with biblios.
190
191 =item export_items
192
193   If this flag is set, the items will be exported.
194   Default is ON.
195
196 =item dont_export_fields
197
198   List of fields not to export.
199
200 =item csv_profile_id
201
202   If the format is csv, a csv_profile_id can be provide to overwrite the default value (syspref ExportWithCsvProfile).
203
204 =cut
205
206 =back
207
208 =head1 LICENSE
209
210 This file is part of Koha.
211
212 Copyright Koha Development Team
213
214 Koha is free software; you can redistribute it and/or modify it
215 under the terms of the GNU General Public License as published by
216 the Free Software Foundation; either version 3 of the License, or
217 (at your option) any later version.
218
219 Koha is distributed in the hope that it will be useful, but
220 WITHOUT ANY WARRANTY; without even the implied warranty of
221 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
222 GNU General Public License for more details.
223
224 You should have received a copy of the GNU General Public License
225 along with Koha; if not, see <http://www.gnu.org/licenses>.