Merge remote-tracking branch 'origin/new/bug_8268'
[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 under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA  02111-1307 USA
18
19
20 use strict;
21 use warnings;
22 use C4::Auth;
23 use C4::Output;
24 use C4::Biblio;  # GetMarcBiblio GetXmlBiblio
25 use C4::AuthoritiesMarc; # GetAuthority
26 use CGI;
27 use C4::Koha;    # GetItemTypes
28 use C4::Branch;  # GetBranches
29 use C4::Record;
30 use Getopt::Long;
31
32 my $query = new CGI;
33
34 my $op;
35 my $filename;
36 my $dbh         = C4::Context->dbh;
37 my $marcflavour = C4::Context->preference("marcflavour");
38 my $clean;
39 my $output_format;
40 my $dont_export_items;
41 my $deleted_barcodes;
42 my $timestamp;
43 my $record_type;
44 my $help;
45
46 # Checks if the script is called from commandline
47 my $commandline = not defined $ENV{GATEWAY_INTERFACE};
48
49 if ( $commandline ) {
50
51     # Getting parameters
52     $op = 'export';
53     GetOptions(
54         'format=s' => \$output_format,
55         'date=s' => \$timestamp,
56         'dont_export_items' => \$dont_export_items,
57         'deleted_barcodes' => \$deleted_barcodes,
58         'clean' => \$clean,
59         'filename=s' => \$filename,
60         'record-type=s' => \$record_type,
61         'help|?' => \$help
62     );
63
64     if ($help) {
65         print <<_USAGE_;
66 export.pl [--format=format] [--date=date] [--record-type=TYPE] [--dont_export_items] [--deleted_barcodes] [--clean] --filename=outputfile
67
68
69  --format=FORMAT        FORMAT is either 'xml' or 'marc' (default)
70
71  --date=DATE            DATE should be entered as the 'dateformat' syspref is
72                         set (dd/mm/yyyy for metric, yyyy-mm-dd for iso,
73                         mm/dd/yyyy for us) records exported are the ones that
74                         have been modified since DATE
75
76  --record-type=TYPE     TYPE is 'bibs' or 'auths'
77
78  --deleted_barcodes     If used, a list of barcodes of items deleted since DATE
79                         is produced (or from all deleted items if no date is
80                         specified). Used only if TYPE is 'bibs'
81
82  --clean                removes NSE/NSB
83 _USAGE_
84         exit;
85     }
86
87     # Default parameters values :
88     $output_format     ||= 'marc';
89     $timestamp         ||= '';
90     $dont_export_items ||= 0;
91     $deleted_barcodes  ||= 0;
92     $clean             ||= 0;
93     $record_type       ||= "bibs";
94
95     # Redirect stdout
96     open STDOUT, '>', $filename if $filename;
97
98 } else {
99
100     $op          = $query->param("op") || '';
101     $filename    = $query->param("filename") || 'koha.mrc';
102     $filename =~ s/(\r|\n)//;
103
104 }
105
106 my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user(
107     {
108         template_name => "tools/export.tmpl",
109         query => $query,
110         type => "intranet",
111         authnotrequired => $commandline,
112         flagsrequired => {tools => 'export_catalog'},
113         debug => 1,
114     }
115 );
116
117 my $limit_ind_branch = (
118     C4::Context->preference('IndependantBranches') &&
119     C4::Context->userenv &&
120     !(C4::Context->userenv->{flags} & 1) &&
121     C4::Context->userenv->{branch}
122 ) ? 1 : 0;
123
124 my $branch = $query->param("branch") || '';
125 if ( C4::Context->preference("IndependantBranches") &&
126      C4::Context->userenv &&
127      !(C4::Context->userenv->{flags} & 1) ) {
128     $branch = C4::Context->userenv->{'branch'};
129 }
130
131 my $backupdir = C4::Context->config('backupdir');
132
133 if ($op eq "export") {
134     my $charset  = 'utf-8';
135     my $mimetype = 'application/octet-stream';
136     binmode STDOUT, ':encoding(UTF-8)';
137     if ( $filename =~ m/\.gz$/ ) {
138         $mimetype = 'application/x-gzip';
139         $charset = '';
140         binmode STDOUT;
141     } elsif ( $filename =~ m/\.bz2$/ ) {
142         $mimetype = 'application/x-bzip2';
143         binmode STDOUT;
144         $charset = '';
145     }
146     print $query->header(
147         -type => $mimetype,
148         -charset => $charset,
149         -attachment => $filename
150     ) unless ($commandline);
151
152     $record_type           = $query->param("record_type") unless ($commandline);
153     $output_format         = $query->param("output_format") || 'marc' unless ($commandline);
154     my $dont_export_fields = $query->param("dont_export_fields");
155     my @sql_params;
156     my $sql_query;
157
158     my $StartingBiblionumber = $query->param("StartingBiblionumber");
159     my $EndingBiblionumber   = $query->param("EndingBiblionumber");
160     my $itemtype             = $query->param("itemtype");
161     my $start_callnumber     = $query->param("start_callnumber");
162     my $end_callnumber       = $query->param("end_callnumber");
163     $timestamp = ($timestamp) ? C4::Dates->new($timestamp) : '' if ($commandline);
164     my $start_accession =
165       ( $query->param("start_accession") )
166       ? C4::Dates->new( $query->param("start_accession") )
167       : '';
168     my $end_accession =
169       ( $query->param("end_accession") )
170       ? C4::Dates->new( $query->param("end_accession") )
171       : '';
172     $dont_export_items    = $query->param("dont_export_item") unless ($commandline);
173     my $strip_nonlocal_items = $query->param("strip_nonlocal_items");
174
175     my $biblioitemstable = ($commandline and $deleted_barcodes)
176                                 ? 'deletedbiblioitems'
177                                 : 'biblioitems';
178     my $itemstable = ($commandline and $deleted_barcodes)
179                                 ? 'deleteditems'
180                                 : 'items';
181
182     my $starting_authid = $query->param('starting_authid');
183     my $ending_authid   = $query->param('ending_authid');
184     my $authtype        = $query->param('authtype');
185
186     if ( $record_type eq 'bibs' ) {
187         if ($timestamp) {
188             # Specific query when timestamp is used
189             # Actually it's used only with CLI and so all previous filters
190             # are not used.
191             # If one day timestamp is used via the web interface, this part will
192             # certainly have to be rewrited
193             $sql_query = " (
194                 SELECT biblionumber
195                 FROM $biblioitemstable
196                   LEFT JOIN items USING(biblionumber)
197                 WHERE $biblioitemstable.timestamp >= ?
198                   OR items.timestamp >= ?
199             ) UNION (
200                 SELECT biblionumber
201                 FROM $biblioitemstable
202                   LEFT JOIN deleteditems USING(biblionumber)
203                 WHERE $biblioitemstable.timestamp >= ?
204                   OR deleteditems.timestamp >= ?
205             ) ";
206             my $ts = $timestamp->output('iso');
207             @sql_params = ($ts, $ts, $ts, $ts);
208         } else {
209             my $items_filter =
210                 $branch || $start_callnumber || $end_callnumber ||
211                 $start_accession || $timestamp || $end_accession ||
212                 ($itemtype && C4::Context->preference('item-level_itypes'));
213             $sql_query = $items_filter ?
214                 "SELECT DISTINCT $biblioitemstable.biblionumber
215                 FROM $biblioitemstable JOIN $itemstable
216                 USING (biblionumber) WHERE 1"
217                 :
218                 "SELECT $biblioitemstable.biblionumber FROM $biblioitemstable WHERE biblionumber >0 ";
219
220             if ( $StartingBiblionumber ) {
221                 $sql_query .= " AND $biblioitemstable.biblionumber >= ? ";
222                 push @sql_params, $StartingBiblionumber;
223             }
224
225             if ( $EndingBiblionumber ) {
226                 $sql_query .= " AND $biblioitemstable.biblionumber <= ? ";
227                 push @sql_params, $EndingBiblionumber;
228             }
229
230             if ($branch) {
231                 $sql_query .= " AND homebranch = ? ";
232                 push @sql_params, $branch;
233             }
234
235             if ($start_callnumber) {
236                 $sql_query .= " AND itemcallnumber <= ? ";
237                 push @sql_params, $start_callnumber;
238             }
239
240             if ($end_callnumber) {
241                 $sql_query .= " AND itemcallnumber >= ? ";
242                 push @sql_params, $end_callnumber;
243             }
244             if ($start_accession) {
245                 $sql_query .= " AND dateaccessioned >= ? ";
246                 push @sql_params, $start_accession->output('iso');
247             }
248
249             if ($end_accession) {
250                 $sql_query .= " AND dateaccessioned <= ? ";
251                 push @sql_params, $end_accession->output('iso');
252             }
253
254             if ( $itemtype ) {
255                 $sql_query .= (C4::Context->preference('item-level_itypes')) ? " AND items.itype = ? " : " AND biblioitems.itemtype = ?";
256                 push @sql_params, $itemtype;
257             }
258         }
259     }
260     elsif ( $record_type eq 'auths' ) {
261         $sql_query =
262           "SELECT DISTINCT auth_header.authid FROM auth_header WHERE 1";
263
264         if ($starting_authid) {
265             $sql_query .= " AND auth_header.authid >= ? ";
266             push @sql_params, $starting_authid;
267         }
268
269         if ($ending_authid) {
270             $sql_query .= " AND auth_header.authid <= ? ";
271             push @sql_params, $ending_authid;
272         }
273
274         if ($authtype) {
275             $sql_query .= " AND auth_header.authtypecode = ? ";
276             push @sql_params, $authtype;
277         }
278     }
279     elsif ( $record_type eq 'db' ) {
280         my $successful_export;
281         if ( $flags->{superlibrarian} && C4::Context->config('backup_db_via_tools') ) {
282             $successful_export = download_backup( { directory => "$backupdir", extension => 'sql', filename => "$filename" } )
283         }
284         unless ( $successful_export ) {
285             my $remotehost = $query->remote_host();
286             $remotehost =~ s/(\n|\r)//;
287             warn "A suspicious attempt was made to download the db at '$filename' by someone at " . $remotehost . "\n";
288         }
289         exit;
290     }
291     elsif ( $record_type eq 'conf' ) {
292         my $successful_export;
293         if ( $flags->{superlibrarian} && C4::Context->config('backup_conf_via_tools') ) {
294             $successful_export = download_backup( { directory => "$backupdir", extension => 'tar', filename => "$filename" } )
295         }
296         unless ( $successful_export ) {
297             my $remotehost = $query->remote_host();
298             $remotehost =~ s/(\n|\r)//;
299             warn "A suspicious attempt was made to download the configuration at '$filename' by someone at " . $remotehost . "\n";
300         }
301         exit;
302     }
303     else {
304         # Someone is trying to mess us up
305         exit;
306     }
307
308     my $sth = $dbh->prepare($sql_query);
309     $sth->execute(@sql_params);
310
311     while ( my ($recordid) = $sth->fetchrow ) {
312         if ( $deleted_barcodes ) {
313             my $q = "
314                 SELECT DISTINCT barcode
315                 FROM deleteditems
316                 WHERE deleteditems.biblionumber = ?
317             ";
318             my $sth = $dbh->prepare($q);
319             $sth->execute($recordid);
320             while (my $row = $sth->fetchrow_array) {
321                 print "$row\n";
322             }
323         } else {
324             my $record;
325             if ( $record_type eq 'bibs' ) {
326                 $record = eval { GetMarcBiblio($recordid); };
327
328                 if ($@) {
329                     next;
330                 }
331                 next if not defined $record;
332                 C4::Biblio::EmbedItemsInMarcBiblio( $record, $recordid )
333                   unless $dont_export_items;
334                 if ( $strip_nonlocal_items || $limit_ind_branch ) {
335                     my ( $homebranchfield, $homebranchsubfield ) =
336                       GetMarcFromKohaField( 'items.homebranch', '' );
337                     for my $itemfield ( $record->field($homebranchfield) ) {
338
339     # if stripping nonlocal items, use loggedinuser's branch if they didn't select one
340                         $branch = C4::Context->userenv->{'branch'} unless $branch;
341                         $record->delete_field($itemfield)
342                           if (
343                             $itemfield->subfield($homebranchsubfield) ne $branch );
344                     }
345                 }
346             }
347             elsif ( $record_type eq 'auths' ) {
348                 $record = C4::AuthoritiesMarc::GetAuthority($recordid);
349                 next if not defined $record;
350             }
351
352             if ( $dont_export_fields ) {
353                 my @fields = split " ", $dont_export_fields;
354                 foreach ( @fields ) {
355                     /^(\d*)(\w)?$/;
356                     my $field = $1;
357                     my $subfield = $2;
358                     # skip if this record doesn't have this field
359                     next if not defined $record->field($field);
360                     if( $subfield ) {
361                         $record->field($field)->delete_subfields($subfield);
362                     }
363                     else {
364                         $record->delete_field($record->field($field));
365                     }
366                 }
367             }
368             RemoveAllNsb($record) if ($clean);
369             if ( $output_format eq "xml" ) {
370                 if ($marcflavour eq 'UNIMARC' && $record_type eq 'auths') {
371                     print $record->as_xml_record('UNIMARCAUTH');
372                 } else {
373                     print $record->as_xml_record($marcflavour);
374                 }
375             }
376             else {
377                 print $record->as_usmarc();
378             }
379         }
380     }
381     exit;
382
383 }    # if export
384
385 else {
386
387     my $itemtypes = GetItemTypes;
388     my @itemtypesloop;
389     foreach my $thisitemtype (sort keys %$itemtypes) {
390         my %row =
391             (
392                 value => $thisitemtype,
393                 description => $itemtypes->{$thisitemtype}->{'description'},
394             );
395        push @itemtypesloop, \%row;
396     }
397     my $branches = GetBranches($limit_ind_branch);
398     my @branchloop;
399     for my $thisbranch (
400         sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} }
401         keys %{$branches}
402       ) {
403         push @branchloop,
404           { value      => $thisbranch,
405             selected   => $thisbranch eq $branch,
406             branchname => $branches->{$thisbranch}->{'branchname'},
407           };
408     }
409
410     my $authtypes = getauthtypes;
411     my @authtypesloop;
412     foreach my $thisauthtype ( sort keys %$authtypes ) {
413         next unless $thisauthtype;
414         my %row = (
415             value       => $thisauthtype,
416             description => $authtypes->{$thisauthtype}->{'authtypetext'},
417         );
418         push @authtypesloop, \%row;
419     }
420
421     if ( $flags->{superlibrarian} && C4::Context->config('backup_db_via_tools') && $backupdir && -d $backupdir ) {
422         $template->{VARS}->{'allow_db_export'} = 1;
423         $template->{VARS}->{'dbfiles'} = getbackupfilelist( { directory => "$backupdir", extension => 'sql' } );
424     }
425
426     if ( $flags->{superlibrarian} && C4::Context->config('backup_conf_via_tools') && $backupdir && -d $backupdir ) {
427         $template->{VARS}->{'allow_conf_export'} = 1;
428         $template->{VARS}->{'conffiles'} = getbackupfilelist( { directory => "$backupdir", extension => 'tar' } );
429     }
430
431     $template->param(
432         branchloop               => \@branchloop,
433         itemtypeloop             => \@itemtypesloop,
434         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
435         authtypeloop             => \@authtypesloop,
436         dont_export_fields       => C4::Context->preference("DontExportFields"),
437     );
438
439     output_html_with_http_headers $query, $cookie, $template->output;
440 }
441
442 sub getbackupfilelist {
443     my $args = shift;
444     my $directory = $args->{directory};
445     my $extension = $args->{extension};
446     my @files;
447
448     if ( opendir(my $dir, $directory) ) {
449         while (my $file = readdir($dir)) {
450             next unless ( $file =~ m/\.$extension(\.(gz|bz2|xz))?/ );
451             push @files, $file if ( -f "$directory/$file" && -r "$directory/$file" );
452         }
453         closedir($dir);
454     }
455     return \@files;
456 }
457
458 sub download_backup {
459     my $args = shift;
460     my $directory = $args->{directory};
461     my $extension = $args->{extension};
462     my $filename  = $args->{filename};
463
464     return unless ( $directory && -d $directory );
465     return unless ( $filename =~ m/\.$extension(\.(gz|bz2|xz))?$/ );
466     return if ( $filename =~ m#/# );
467     $filename = "$directory/$filename";
468     return unless ( -f $filename && -r $filename );
469     return unless ( open(my $dump, '<', $filename) );
470     binmode $dump;
471     while (read($dump, my $data, 64 * 1024)) {
472         print $data;
473     }
474     close ($dump);
475     return 1;
476 }