Bug 16699: Remove requirement from borrowernumberQueryParam
[koha.git] / tools / export.pl
blob46cca208c5685b1b1fb9ed5c9bfe5c8a9abccca4
1 #!/usr/bin/perl
4 # This file is part of Koha.
6 # Koha is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # Koha is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19 use Modern::Perl;
20 use CGI qw ( -utf8 );
21 use MARC::File::XML;
22 use List::MoreUtils qw(uniq);
23 use C4::Auth;
24 use C4::Branch; # GetBranches
25 use C4::Koha; # GetItemTypes
26 use C4::Output;
28 use Koha::Authority::Types;
29 use Koha::Biblioitems;
30 use Koha::CsvProfiles;
31 use Koha::Database;
32 use Koha::DateUtils qw( dt_from_string output_pref );
33 use Koha::Exporter::Record;
35 my $query = new CGI;
37 my $dont_export_items = $query->param("dont_export_item") || 0;
38 my $record_type = $query->param("record_type");
39 my $op = $query->param("op") || '';
40 my $output_format = $query->param("format") || $query->param("output_format") || 'iso2709';
41 my $backupdir = C4::Context->config('backupdir');
42 my $filename = $query->param("filename") || 'koha.mrc';
43 $filename =~ s/(\r|\n)//;
45 my $dbh = C4::Context->dbh;
47 my @record_ids;
48 # biblionumbers is sent from circulation.pl only
49 if ( $query->param("biblionumbers") ) {
50 $record_type = 'bibs';
51 @record_ids = $query->multi_param("biblionumbers");
54 # Default value for output_format is 'iso2709'
55 $output_format ||= 'iso2709';
56 # Retrocompatibility for the format parameter
57 $output_format = 'iso2709' if $output_format eq 'marc';
59 my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user(
61 template_name => "tools/export.tt",
62 query => $query,
63 type => "intranet",
64 authnotrequired => 0,
65 flagsrequired => { tools => 'export_catalog' },
66 debug => 1,
70 my @branch = $query->multi_param("branch");
71 my $only_my_branch;
72 # Limit to local branch if IndependentBranches and not superlibrarian
73 if (
75 C4::Context->preference('IndependentBranches')
76 && C4::Context->userenv
77 && !C4::Context->IsSuperLibrarian()
78 && C4::Context->userenv->{branch}
80 # Limit result to local branch strip_nonlocal_items
81 or $query->param('strip_nonlocal_items')
82 ) {
83 $only_my_branch = 1;
84 @branch = ( C4::Context->userenv->{'branch'} );
87 my %branchmap = map { $_ => 1 } @branch; # for quick lookups
89 if ( $op eq "export" ) {
91 my $export_remove_fields = $query->param("export_remove_fields") || q||;
92 my @biblionumbers = $query->multi_param("biblionumbers");
93 my @itemnumbers = $query->multi_param("itemnumbers");
94 my @sql_params;
95 my $sql_query;
97 if ( $record_type eq 'bibs' or $record_type eq 'auths' ) {
98 # No need to retrieve the record_ids if we already get them
99 unless ( @record_ids ) {
100 if ( $record_type eq 'bibs' ) {
101 my $starting_biblionumber = $query->param("StartingBiblionumber");
102 my $ending_biblionumber = $query->param("EndingBiblionumber");
103 my $itemtype = $query->param("itemtype");
104 my $start_callnumber = $query->param("start_callnumber");
105 my $end_callnumber = $query->param("end_callnumber");
106 my $start_accession =
107 ( $query->param("start_accession") )
108 ? dt_from_string( scalar $query->param("start_accession") )
109 : '';
110 my $end_accession =
111 ( $query->param("end_accession") )
112 ? dt_from_string( scalar $query->param("end_accession") )
113 : '';
116 my $conditions = {
117 ( $starting_biblionumber or $ending_biblionumber )
119 "me.biblionumber" => {
120 ( $starting_biblionumber ? ( '>=' => $starting_biblionumber ) : () ),
121 ( $ending_biblionumber ? ( '<=' => $ending_biblionumber ) : () ),
124 : (),
126 ( $start_callnumber or $end_callnumber )
128 'items.itemcallnumber' => {
129 ( $start_callnumber ? ( '>=' => $start_callnumber ) : () ),
130 ( $end_callnumber ? ( '<=' => $end_callnumber ) : () ),
133 : (),
135 ( $start_accession or $end_accession )
137 'items.dateaccessioned' => {
138 ( $start_accession ? ( '>=' => $start_accession ) : () ),
139 ( $end_accession ? ( '<=' => $end_accession ) : () ),
142 : (),
143 ( @branch ? ( 'items.homebranch' => { in => \@branch } ) : () ),
144 ( $itemtype
146 C4::Context->preference('item-level_itypes')
147 ? ( 'items.itype' => $itemtype )
148 : ( 'biblioitems.itemtype' => $itemtype )
149 : ()
153 my $biblioitems = Koha::Biblioitems->search( $conditions, { join => 'items', columns => 'biblionumber' } );
154 while ( my $biblioitem = $biblioitems->next ) {
155 push @record_ids, $biblioitem->biblionumber;
158 elsif ( $record_type eq 'auths' ) {
159 my $starting_authid = $query->param('starting_authid');
160 my $ending_authid = $query->param('ending_authid');
161 my $authtype = $query->param('authtype');
163 my $conditions = {
164 ( $starting_authid or $ending_authid )
166 authid => {
167 ( $starting_authid ? ( '>=' => $starting_authid ) : () ),
168 ( $ending_authid ? ( '<=' => $ending_authid ) : () ),
171 : (),
172 ( $authtype ? ( authtypecode => $authtype ) : () ),
174 # Koha::MetadataRecord::Authority is not a Koha::Object...
175 my $authorities = Koha::Database->new->schema->resultset('AuthHeader')->search( $conditions );
176 @record_ids = map { $_->authid } $authorities->all;
180 @record_ids = uniq @record_ids;
181 if ( @record_ids and my $filefh = $query->upload("id_list_file") ) {
182 my @filter_record_ids = <$filefh>;
183 @filter_record_ids = map { my $id = $_; $id =~ s/[\r\n]*$//; $id } @filter_record_ids;
184 # intersection
185 my %record_ids = map { $_ => 1 } @record_ids;
186 @record_ids = grep $record_ids{$_}, @filter_record_ids;
189 print CGI->new->header(
190 -type => 'application/octet-stream',
191 -charset => 'utf-8',
192 -attachment => $filename,
195 my $csv_profile_id = $query->param('csv_profile_id');
196 unless ( $csv_profile_id ) {
197 # FIXME export_format.profile should be a unique key
198 my $default_csv_profiles = Koha::CsvProfiles->search({ profile => C4::Context->preference('ExportWithCsvProfile') });
199 $csv_profile_id = $default_csv_profiles->count ? $default_csv_profiles->next->export_format_id : undef;
202 Koha::Exporter::Record::export(
203 { record_type => $record_type,
204 record_ids => \@record_ids,
205 format => $output_format,
206 filename => $filename,
207 itemnumbers => \@itemnumbers,
208 dont_export_fields => $export_remove_fields,
209 csv_profile_id => $csv_profile_id,
210 export_items => (not $dont_export_items),
214 elsif ( $record_type eq 'db' or $record_type eq 'conf' ) {
215 my $successful_export;
217 if ( $flags->{superlibrarian}
218 and (
219 $record_type eq 'db' and C4::Context->config('backup_db_via_tools')
221 $record_type eq 'conf' and C4::Context->config('backup_conf_via_tools')
224 binmode STDOUT, ':encoding(UTF-8)';
226 my $charset = 'utf-8';
227 my $mimetype = 'application/octet-stream';
228 if ( $filename =~ m/\.gz$/ ) {
229 $mimetype = 'application/x-gzip';
230 $charset = '';
231 binmode STDOUT;
233 elsif ( $filename =~ m/\.bz2$/ ) {
234 $mimetype = 'application/x-bzip2';
235 binmode STDOUT;
236 $charset = '';
238 print $query->header(
239 -type => $mimetype,
240 -charset => $charset,
241 -attachment => $filename,
244 my $extension = $record_type eq 'db' ? 'sql' : 'tar';
246 $successful_export = download_backup(
248 directory => $backupdir,
249 extension => $extension,
250 filename => $filename,
253 unless ($successful_export) {
254 my $remotehost = $query->remote_host();
255 $remotehost =~ s/(\n|\r)//;
256 warn
257 "A suspicious attempt was made to download the " . ( $record_type eq 'db' ? 'db' : 'configuration' ) . "at '$filename' by someone at "
258 . $remotehost . "\n";
263 exit;
266 else {
268 my $itemtypes = GetItemTypes;
269 my @itemtypesloop;
270 foreach my $thisitemtype ( sort keys %$itemtypes ) {
271 my %row = (
272 value => $thisitemtype,
273 description => $itemtypes->{$thisitemtype}->{translated_description},
275 push @itemtypesloop, \%row;
277 my $branches = GetBranches($only_my_branch);
278 my @branchloop;
279 for my $thisbranch (
280 sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} }
281 keys %{$branches}
284 push @branchloop,
286 value => $thisbranch,
287 selected => %branchmap ? $branchmap{$thisbranch} : 1,
288 branchname => $branches->{$thisbranch}->{'branchname'},
292 my $authority_types = Koha::Authority::Types->search( {}, { order_by => ['authtypecode'] } );
294 if ( $flags->{superlibrarian}
295 && C4::Context->config('backup_db_via_tools')
296 && $backupdir
297 && -d $backupdir )
299 $template->{VARS}->{'allow_db_export'} = 1;
300 $template->{VARS}->{'dbfiles'} = getbackupfilelist(
301 { directory => "$backupdir", extension => 'sql' } );
304 if ( $flags->{superlibrarian}
305 && C4::Context->config('backup_conf_via_tools')
306 && $backupdir
307 && -d $backupdir )
309 $template->{VARS}->{'allow_conf_export'} = 1;
310 $template->{VARS}->{'conffiles'} = getbackupfilelist(
311 { directory => "$backupdir", extension => 'tar' } );
314 $template->param(
315 branchloop => \@branchloop,
316 itemtypeloop => \@itemtypesloop,
317 authority_types => $authority_types,
318 export_remove_fields => C4::Context->preference("ExportRemoveFields"),
319 csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ],
322 output_html_with_http_headers $query, $cookie, $template->output;
325 sub getbackupfilelist {
326 my $args = shift;
327 my $directory = $args->{directory};
328 my $extension = $args->{extension};
329 my @files;
331 if ( opendir( my $dir, $directory ) ) {
332 while ( my $file = readdir($dir) ) {
333 next unless ( $file =~ m/\.$extension(\.(gz|bz2|xz))?/ );
334 push @files, $file
335 if ( -f "$directory/$file" && -r "$directory/$file" );
337 closedir($dir);
339 return \@files;
342 sub download_backup {
343 my $args = shift;
344 my $directory = $args->{directory};
345 my $extension = $args->{extension};
346 my $filename = $args->{filename};
348 return unless ( $directory && -d $directory );
349 return unless ( $filename =~ m/\.$extension(\.(gz|bz2|xz))?$/ );
350 return if ( $filename =~ m#/# );
351 $filename = "$directory/$filename";
352 return unless ( -f $filename && -r $filename );
353 return unless ( open( my $dump, '<', $filename ) );
354 binmode $dump;
356 while ( read( $dump, my $data, 64 * 1024 ) ) {
357 print $data;
359 close($dump);
360 return 1;