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