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