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