Bug 18897: Improve error message
[koha.git] / tools / export.pl
1 #!/usr/bin/perl
2
3 #
4 # This file is part of Koha.
5 #
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.
10 #
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.
15 #
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>.
18
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::Koha;               # GetItemTypes
25 use C4::Output;
26
27 use Koha::Authority::Types;
28 use Koha::Biblioitems;
29 use Koha::CsvProfiles;
30 use Koha::Database;
31 use Koha::DateUtils qw( dt_from_string output_pref );
32 use Koha::Exporter::Record;
33 use Koha::Libraries;
34
35 my $query = new CGI;
36
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") || ( $output_format eq 'csv' ? 'koha.csv' : 'koha.mrc' );
43 $filename =~ s/(\r|\n)//;
44
45 my $dbh = C4::Context->dbh;
46
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");
52 }
53
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';
58
59 my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user(
60     {
61         template_name   => "tools/export.tt",
62         query           => $query,
63         type            => "intranet",
64         authnotrequired => 0,
65         flagsrequired   => { tools => 'export_catalog' },
66         debug           => 1,
67     }
68 );
69
70 my @branch = $query->multi_param("branch");
71
72 my @messages;
73 if ( $op eq 'export' ) {
74     my $filename = $query->param('id_list_file');
75     if ( $filename ) {
76         my $mimetype = $query->uploadInfo($filename)->{'Content-Type'};
77         my @valid_mimetypes = qw( application/octet-stream text/csv text/plain application/vnd.ms-excel );
78         unless ( grep { /^$mimetype$/ } @valid_mimetypes ) {
79             push @messages, { type => 'alert', code => 'invalid_mimetype' };
80             $op = '';
81         }
82     }
83 }
84
85 if ( $op eq "export" ) {
86
87     my $export_remove_fields = $query->param("export_remove_fields") || q||;
88     my @biblionumbers      = $query->multi_param("biblionumbers");
89     my @itemnumbers        = $query->multi_param("itemnumbers");
90     my $strip_nonlocal_items =  $query->param('strip_nonlocal_items');
91     my @sql_params;
92     my $sql_query;
93
94     my $libraries = $strip_nonlocal_items
95         ? [ Koha::Libraries->find(C4::Context->userenv->{branch})->unblessed ]
96         : Koha::Libraries->search_filtered->unblessed;
97     my @branchcodes;
98     for my $branchcode ( @branch ) {
99         if ( grep { $_->{branchcode} eq $branchcode } @$libraries ) {
100             push @branchcodes, $branchcode;
101         }
102     }
103
104     if ( $record_type eq 'bibs' or $record_type eq 'auths' ) {
105         # No need to retrieve the record_ids if we already get them
106         unless ( @record_ids ) {
107             if ( $record_type eq 'bibs' ) {
108                 my $starting_biblionumber = $query->param("StartingBiblionumber");
109                 my $ending_biblionumber   = $query->param("EndingBiblionumber");
110                 my $itemtype             = $query->param("itemtype");
111                 my $start_callnumber     = $query->param("start_callnumber");
112                 my $end_callnumber       = $query->param("end_callnumber");
113                 my $start_accession =
114                   ( $query->param("start_accession") )
115                   ? dt_from_string( scalar $query->param("start_accession") )
116                   : '';
117                 my $end_accession =
118                   ( $query->param("end_accession") )
119                   ? dt_from_string( scalar $query->param("end_accession") )
120                   : '';
121
122
123                 my $conditions = {
124                     ( $starting_biblionumber or $ending_biblionumber )
125                         ? (
126                             "me.biblionumber" => {
127                                 ( $starting_biblionumber ? ( '>=' => $starting_biblionumber ) : () ),
128                                 ( $ending_biblionumber   ? ( '<=' => $ending_biblionumber   ) : () ),
129                             }
130                         )
131                         : (),
132
133                     ( $start_callnumber or $end_callnumber )
134                         ? (
135                             'items.itemcallnumber' => {
136                                 ( $start_callnumber ? ( '>=' => $start_callnumber ) : () ),
137                                 ( $end_callnumber   ? ( '<=' => $end_callnumber   ) : () ),
138                             }
139                         )
140                         : (),
141
142                     ( $start_accession or $end_accession )
143                         ? (
144                             'items.dateaccessioned' => {
145                                 ( $start_accession ? ( '>=' => $start_accession ) : () ),
146                                 ( $end_accession   ? ( '<=' => $end_accession   ) : () ),
147                             }
148                         )
149                         : (),
150                     ( @branchcodes ? ( 'items.homebranch' => { in => \@branchcodes } ) : () ),
151                     ( $itemtype
152                         ?
153                           C4::Context->preference('item-level_itypes')
154                             ? ( 'items.itype' => $itemtype )
155                             : ( 'me.itemtype' => $itemtype )
156                         : ()
157                     ),
158
159                 };
160                 my $biblioitems = Koha::Biblioitems->search( $conditions, { join => 'items', columns => 'biblionumber' } );
161                 while ( my $biblioitem = $biblioitems->next ) {
162                     push @record_ids, $biblioitem->biblionumber;
163                 }
164             }
165             elsif ( $record_type eq 'auths' ) {
166                 my $starting_authid = $query->param('starting_authid');
167                 my $ending_authid   = $query->param('ending_authid');
168                 my $authtype        = $query->param('authtype');
169
170                 my $conditions = {
171                     ( $starting_authid or $ending_authid )
172                         ? (
173                             authid => {
174                                 ( $starting_authid ? ( '>=' => $starting_authid ) : () ),
175                                 ( $ending_authid   ? ( '<=' => $ending_authid   ) : () ),
176                             }
177                         )
178                         : (),
179                     ( $authtype ? ( authtypecode => $authtype ) : () ),
180                 };
181                 # Koha::MetadataRecord::Authority is not a Koha::Object...
182                 my $authorities = Koha::Database->new->schema->resultset('AuthHeader')->search( $conditions );
183                 @record_ids = map { $_->authid } $authorities->all;
184             }
185         }
186
187         @record_ids = uniq @record_ids;
188         if ( @record_ids and my $filefh = $query->upload("id_list_file") ) {
189             my @filter_record_ids = <$filefh>;
190             @filter_record_ids = map { my $id = $_; $id =~ s/[\r\n]*$//; $id } @filter_record_ids;
191             # intersection
192             my %record_ids = map { $_ => 1 } @record_ids;
193             @record_ids = grep $record_ids{$_}, @filter_record_ids;
194         }
195
196         print CGI->new->header(
197             -type       => 'application/octet-stream',
198             -charset    => 'utf-8',
199             -attachment => $filename,
200         );
201
202         my $csv_profile_id = $query->param('csv_profile_id');
203         unless ( $csv_profile_id ) {
204             # FIXME export_format.profile should be a unique key
205             my $default_csv_profiles = Koha::CsvProfiles->search({ profile => C4::Context->preference('ExportWithCsvProfile') });
206             $csv_profile_id = $default_csv_profiles->count ? $default_csv_profiles->next->export_format_id : undef;
207         }
208
209         Koha::Exporter::Record::export(
210             {   record_type        => $record_type,
211                 record_ids         => \@record_ids,
212                 format             => $output_format,
213                 filename           => $filename,
214                 itemnumbers        => \@itemnumbers,
215                 dont_export_fields => $export_remove_fields,
216                 csv_profile_id     => $csv_profile_id,
217                 export_items       => (not $dont_export_items),
218             }
219         );
220     }
221     elsif ( $record_type eq 'db' or $record_type eq 'conf' ) {
222         my $successful_export;
223
224         if ( $flags->{superlibrarian}
225             and (
226                     $record_type eq 'db' and C4::Context->config('backup_db_via_tools')
227                  or
228                     $record_type eq 'conf' and C4::Context->config('backup_conf_via_tools')
229             )
230         ) {
231             binmode STDOUT, ':encoding(UTF-8)';
232
233             my $charset  = 'utf-8';
234             my $mimetype = 'application/octet-stream';
235             if ( $filename =~ m/\.gz$/ ) {
236                 $mimetype = 'application/x-gzip';
237                 $charset  = '';
238                 binmode STDOUT;
239             }
240             elsif ( $filename =~ m/\.bz2$/ ) {
241                 $mimetype = 'application/x-bzip2';
242                 binmode STDOUT;
243                 $charset = '';
244             }
245             print $query->header(
246                 -type       => $mimetype,
247                 -charset    => $charset,
248                 -attachment => $filename,
249             );
250
251             my $extension = $record_type eq 'db' ? 'sql' : 'tar';
252
253             $successful_export = download_backup(
254                 {
255                     directory => $backupdir,
256                     extension => $extension,
257                     filename  => $filename,
258                 }
259             );
260             unless ($successful_export) {
261                 my $remotehost = $query->remote_host();
262                 $remotehost =~ s/(\n|\r)//;
263                 warn
264     "A suspicious attempt was made to download the " . ( $record_type eq 'db' ? 'db' : 'configuration' ) . "at '$filename' by someone at "
265                   . $remotehost . "\n";
266             }
267         }
268     }
269
270     exit;
271 }
272
273 else {
274
275     my $itemtypes = GetItemTypes;
276     my @itemtypesloop;
277     foreach my $thisitemtype ( sort keys %$itemtypes ) {
278         my %row = (
279             value       => $thisitemtype,
280             description => $itemtypes->{$thisitemtype}->{translated_description},
281         );
282         push @itemtypesloop, \%row;
283     }
284
285     my $authority_types = Koha::Authority::Types->search( {}, { order_by => ['authtypecode'] } );
286
287     my $libraries = Koha::Libraries->search_filtered({}, { order_by => ['branchname'] })->unblessed;
288     for my $library ( @$libraries ) {
289         $library->{selected} = 1 if grep { $library->{branchcode} eq $_ } @branch;
290     }
291
292     if (   $flags->{superlibrarian}
293         && C4::Context->config('backup_db_via_tools')
294         && $backupdir
295         && -d $backupdir )
296     {
297         $template->{VARS}->{'allow_db_export'} = 1;
298         $template->{VARS}->{'dbfiles'}         = getbackupfilelist(
299             { directory => "$backupdir", extension => 'sql' } );
300     }
301
302     if (   $flags->{superlibrarian}
303         && C4::Context->config('backup_conf_via_tools')
304         && $backupdir
305         && -d $backupdir )
306     {
307         $template->{VARS}->{'allow_conf_export'} = 1;
308         $template->{VARS}->{'conffiles'}         = getbackupfilelist(
309             { directory => "$backupdir", extension => 'tar' } );
310     }
311
312     $template->param(
313         libraries                => $libraries,
314         itemtypeloop             => \@itemtypesloop,
315         authority_types          => $authority_types,
316         export_remove_fields     => C4::Context->preference("ExportRemoveFields"),
317         csv_profiles             => [ Koha::CsvProfiles->search({ type => 'marc' }) ],
318         messages                 => \@messages,
319     );
320
321     output_html_with_http_headers $query, $cookie, $template->output;
322 }
323
324 sub getbackupfilelist {
325     my $args      = shift;
326     my $directory = $args->{directory};
327     my $extension = $args->{extension};
328     my @files;
329
330     if ( opendir( my $dir, $directory ) ) {
331         while ( my $file = readdir($dir) ) {
332             next unless ( $file =~ m/\.$extension(\.(gz|bz2|xz))?/ );
333             push @files, $file
334               if ( -f "$directory/$file" && -r "$directory/$file" );
335         }
336         closedir($dir);
337     }
338     return \@files;
339 }
340
341 sub download_backup {
342     my $args      = shift;
343     my $directory = $args->{directory};
344     my $extension = $args->{extension};
345     my $filename  = $args->{filename};
346
347     return unless ( $directory && -d $directory );
348     return unless ( $filename =~ m/\.$extension(\.(gz|bz2|xz))?$/ );
349     return if ( $filename =~ m#/# );
350     $filename = "$directory/$filename";
351     return unless ( -f $filename && -r $filename );
352     return unless ( open( my $dump, '<', $filename ) );
353     binmode $dump;
354
355     while ( read( $dump, my $data, 64 * 1024 ) ) {
356         print $data;
357     }
358     close($dump);
359     return 1;
360 }