Update release notes for 22.11.17 release
[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 qw( get_template_and_user );
24 use C4::Output qw( output_html_with_http_headers );
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 );
31 use Koha::Exporter::Record;
32 use Koha::ItemTypes;
33 use Koha::Libraries;
34
35 my $query = CGI->new;
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 && $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         flagsrequired   => { tools => 'export_catalog' },
70     }
71 );
72
73 my @branch = $query->multi_param("branch");
74
75 my @messages;
76 if ( $op eq 'export' ) {
77     my $filename = $query->param('id_list_file');
78     if ( $filename ) {
79         my $mimetype = $query->uploadInfo($filename)->{'Content-Type'};
80         my @valid_mimetypes = qw( application/octet-stream text/csv text/plain application/vnd.ms-excel );
81         unless ( grep { $_ eq $mimetype } @valid_mimetypes ) {
82             push @messages, { type => 'alert', code => 'invalid_mimetype' };
83             $op = '';
84         }
85     }
86 }
87
88 if ( $op eq "export" ) {
89
90     my $export_remove_fields = $query->param("export_remove_fields") || q||;
91     my @biblionumbers      = $query->multi_param("biblionumbers");
92     my @itemnumbers        = $query->multi_param("itemnumbers");
93     my $strip_items_not_from_libraries =  $query->param('strip_items_not_from_libraries');
94
95     my $libraries = Koha::Libraries->search_filtered->unblessed;
96     my $only_export_items_for_branches = $strip_items_not_from_libraries ? \@branch : undef;
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
109                 my %it_map = map { $_->itemtype => 1 } Koha::ItemTypes->search->as_list;
110                 my @itemtypes = map { $it_map{$_} ? $_ : () } $query->multi_param('itemtype'); #Validate inputs against map
111
112                 my $starting_biblionumber = $query->param("StartingBiblionumber");
113                 my $ending_biblionumber   = $query->param("EndingBiblionumber");
114                 my $start_callnumber     = $query->param("start_callnumber");
115                 my $end_callnumber       = $query->param("end_callnumber");
116                 my $start_accession =
117                   ( $query->param("start_accession") )
118                   ? dt_from_string( scalar $query->param("start_accession") )
119                   : '';
120                 my $end_accession =
121                   ( $query->param("end_accession") )
122                   ? dt_from_string( scalar $query->param("end_accession") )
123                   : '';
124
125
126                 my $conditions = {
127                     ( $starting_biblionumber or $ending_biblionumber )
128                         ? (
129                             "me.biblionumber" => {
130                                 ( $starting_biblionumber ? ( '>=' => $starting_biblionumber ) : () ),
131                                 ( $ending_biblionumber   ? ( '<=' => $ending_biblionumber   ) : () ),
132                             }
133                         )
134                         : (),
135
136                     ( $start_callnumber or $end_callnumber )
137                         ? (
138                             'items.itemcallnumber' => {
139                                 ( $start_callnumber ? ( '>=' => $start_callnumber ) : () ),
140                                 ( $end_callnumber   ? ( '<=' => $end_callnumber   ) : () ),
141                             }
142                         )
143                         : (),
144
145                     ( $start_accession or $end_accession )
146                         ? (
147                             'items.dateaccessioned' => {
148                                 ( $start_accession ? ( '>=' => $start_accession ) : () ),
149                                 ( $end_accession   ? ( '<=' => $end_accession   ) : () ),
150                             }
151                         )
152                         : (),
153                     ( @branchcodes ? ( 'items.homebranch' => { in => \@branchcodes } ) : () ),
154                     ( @itemtypes
155                         ?
156                           C4::Context->preference('item-level_itypes')
157                             ? ( 'items.itype' => { in => \@itemtypes } )
158                             : ( 'me.itemtype' => { in => \@itemtypes } )
159                         : ()
160                     ),
161
162                 };
163                 my $biblioitems = Koha::Biblioitems->search( $conditions, { join => 'items', columns => 'biblionumber' } );
164                 while ( my $biblioitem = $biblioitems->next ) {
165                     push @record_ids, $biblioitem->biblionumber;
166                 }
167             }
168             elsif ( $record_type eq 'auths' ) {
169                 my $starting_authid = $query->param('starting_authid');
170                 my $ending_authid   = $query->param('ending_authid');
171                 my $authtype        = $query->param('authtype');
172
173                 my $conditions = {
174                     ( $starting_authid or $ending_authid )
175                         ? (
176                             authid => {
177                                 ( $starting_authid ? ( '>=' => $starting_authid ) : () ),
178                                 ( $ending_authid   ? ( '<=' => $ending_authid   ) : () ),
179                             }
180                         )
181                         : (),
182                     ( $authtype ? ( authtypecode => $authtype ) : () ),
183                 };
184                 # Koha::MetadataRecord::Authority is not a Koha::Object...
185                 my $authorities = Koha::Database->new->schema->resultset('AuthHeader')->search( $conditions );
186                 @record_ids = map { $_->authid } $authorities->all;
187             }
188         }
189
190         @record_ids = uniq @record_ids;
191         if ( @record_ids and my $filefh = $query->upload("id_list_file") ) {
192             my @filter_record_ids = <$filefh>;
193             @filter_record_ids = map { my $id = $_; $id =~ s/[\r\n]*$//; $id } @filter_record_ids;
194             # intersection
195             my %record_ids = map { $_ => 1 } @record_ids;
196             @record_ids = grep $record_ids{$_}, @filter_record_ids;
197         }
198
199         print CGI->new->header(
200             -type       => 'application/octet-stream',
201             -charset    => 'utf-8',
202             -attachment => $filename,
203         );
204
205         my $csv_profile_id = $query->param('csv_profile_id');
206         Koha::Exporter::Record::export(
207             {   record_type        => $record_type,
208                 record_ids         => \@record_ids,
209                 format             => $output_format,
210                 filename           => $filename,
211                 itemnumbers        => \@itemnumbers,
212                 dont_export_fields => $export_remove_fields,
213                 csv_profile_id     => $csv_profile_id,
214                 export_items       => (not $dont_export_items),
215                 only_export_items_for_branches => $only_export_items_for_branches,
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 = Koha::ItemTypes->search_with_localization;
274
275     my $authority_types = Koha::Authority::Types->search( {}, { order_by => ['authtypecode'] } );
276
277     my $libraries = Koha::Libraries->search_filtered({}, { order_by => ['branchname'] })->unblessed;
278     for my $library ( @$libraries ) {
279         $library->{selected} = 1 if grep { $library->{branchcode} eq $_ } @branch;
280     }
281
282     if (   $flags->{superlibrarian}
283         && C4::Context->config('backup_db_via_tools')
284         && $backupdir
285         && -d $backupdir )
286     {
287         $template->{VARS}->{'allow_db_export'} = 1;
288         $template->{VARS}->{'dbfiles'}         = getbackupfilelist(
289             { directory => "$backupdir", extension => 'sql' } );
290     }
291
292     if (   $flags->{superlibrarian}
293         && C4::Context->config('backup_conf_via_tools')
294         && $backupdir
295         && -d $backupdir )
296     {
297         $template->{VARS}->{'allow_conf_export'} = 1;
298         $template->{VARS}->{'conffiles'}         = getbackupfilelist(
299             { directory => "$backupdir", extension => 'tar' } );
300     }
301
302     $template->param(
303         libraries                => $libraries,
304         itemtypes                => $itemtypes,
305         authority_types          => $authority_types,
306         export_remove_fields     => C4::Context->preference("ExportRemoveFields"),
307         csv_profiles             => [ Koha::CsvProfiles->search({ type => 'marc', used_for => 'export_records' })->as_list ],
308         messages                 => \@messages,
309     );
310
311     output_html_with_http_headers $query, $cookie, $template->output;
312 }
313
314 sub getbackupfilelist {
315     my $args      = shift;
316     my $directory = $args->{directory};
317     my $extension = $args->{extension};
318     my @files;
319
320     if ( opendir( my $dir, $directory ) ) {
321         while ( my $file = readdir($dir) ) {
322             next unless ( $file =~ m/\.$extension(\.(gz|bz2|xz))?/ );
323             push @files, $file
324               if ( -f "$directory/$file" && -r "$directory/$file" );
325         }
326         closedir($dir);
327     }
328     return \@files;
329 }
330
331 sub download_backup {
332     my $args      = shift;
333     my $directory = $args->{directory};
334     my $extension = $args->{extension};
335     my $filename  = $args->{filename};
336
337     return unless ( $directory && -d $directory );
338     return unless ( $filename =~ m/\.$extension(\.(gz|bz2|xz))?$/ );
339     return if ( $filename =~ m#/# );
340     $filename = "$directory/$filename";
341     return unless ( -f $filename && -r $filename );
342     return unless ( open( my $dump, '<', $filename ) );
343     binmode $dump;
344
345     while ( read( $dump, my $data, 64 * 1024 ) ) {
346         print $data;
347     }
348     close($dump);
349     return 1;
350 }