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